﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using RN.ERP.DAL.LcDAL;
using Fly.Log;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using RN.ERP.DAL.Context;
using RN.ERP.Entity.ZBDLRY;
using Fly.FlyCommon;
using RN.ERP.BLL.LC.Utilities;
using RN.ERP.DTO;
using Fly.Common.Linq;
using System.Data;
using System.Data.Entity;
using Fly.Common.WorkFlow;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using RN.ERP.DTO.Person;
using RN.ERP.DTO.EnterpriseModel;

namespace RN.ERP.BLL.LC
{
    public class PersonBLL : BasePersonBLL
    {
        #region dbContext
        private ZBDL_Context zbdlcontext
        {
            get
            {
                return (ZBDL_Context)base.baseContext;
            }
        }
        private LogAndFlowHelper loghelper = new LogAndFlowHelper();
        public PersonBLL()
        {
            base.baseContext = new ZBDL_Context();
        }
        #endregion

        #region 压证相关 无变动

        protected override IQueryable<DTO.V_CheckXMFZR> GetXMFZRQuery()
        {
            var dbUsers = zbdlcontext.T_Sys_Users;
            var dbEmp = zbdlcontext.Emp_Manager;
            var dbTitleDetails = zbdlcontext.Emp_Qualities;
            var rst = from users in dbUsers
                      join emps in dbEmp on users.UserGuid equals emps.CorpGuid
                      join details in dbTitleDetails on emps.EmpGuid equals details.EmpGuid
                      select new DTO.V_CheckXMFZR()
                      {
                          ID = emps.ID,
                          EmpGuid = emps.EmpGuid,
                          // ITypeFlag = details.TypeFlags,
                          TypeFlag = System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)details.TypeFlags).Trim(),
                          bGrade = users.RoleID,
                          CertificateLevel = details.CertificateLevel,
                          EmpName = emps.Name
                      };
            return rst;
        }

        /// <summary>
        /// 人员押证查询-获取人员信息(多项)
        /// 返回字符样式：
        /// 成功：0,empID:typeFlag:Bgrade:CertificateLevel|empID:typeFlag:Bgrade:CertificateLevel
        /// 失败：1,XXXXX
        /// </summary>
        /// <param name="empIds"></param>
        /// <returns></returns>
        public override string GetPersonForXMFZR(string empIds, string areaCode)
        {
            string result = string.Empty;

            IList<Guid> empGuids = new List<Guid>();
            if (string.IsNullOrEmpty(empIds))
            {
                result = "9,人员empGuid不能为空.";
            }
            else
            {
                foreach (string empId in empIds.Split(','))
                {
                    Guid empGuid = Guid.Empty;
                    Guid.TryParse(empId, out empGuid);
                    empGuids.Add(empGuid);
                }

                IList<DTO.V_CheckXMFZR> managers = GetXMFZRQuery().Where(p => empGuids.Contains(p.EmpGuid)).ToList();
                foreach (DTO.V_CheckXMFZR item in managers)
                {
                    string bGrade = "0";
                    if (item.bGrade != null)
                    {
                        bGrade = item.bGrade.ToString();
                    }
                    ////返回人员信息，作为项目库中查询押证的参数
                    result = item.ID + ":" + item.TypeFlag + ":" + bGrade + ":" + item.CertificateLevel + ":" + item.EmpName + "|";
                }
                if (!string.IsNullOrEmpty(result))
                {
                    result = result.TrimEnd('|');
                }
                result = "0," + result;
            }
            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// 人员押证查询-获取人员信息--2013-5-14修改，人员押证在项目库中验证
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        public override string CheckXMFZR(string empId)
        {
            string result = string.Empty;
            Guid empGuid = Guid.Empty;
            int empIntId = 0;
            if (string.IsNullOrEmpty(empId))
            {
                result = "9,参数不能为空.";
                return JsonConvert.SerializeObject(result);
            }
            if (!Guid.TryParse(empId, out empGuid))
            {
                if (int.TryParse(empId, out empIntId))
                {
                    empGuid = GetXMFZRQuery().Where(p => p.ID == empIntId).Select(p => p.EmpGuid).FirstOrDefault();
                    if (empGuid == Guid.Empty)
                    {
                        result = "9,人员empGuid不能为空.";
                        return JsonConvert.SerializeObject(result);
                    }
                }
                else
                {
                    result = "9,传入的参数格式不正确.";
                    return JsonConvert.SerializeObject(result);
                }
            }
            IList<DTO.V_CheckXMFZR> managers = new List<DTO.V_CheckXMFZR>();
            string[] typeFlag = { "0", "1011", "1" };////人员类型是项目经理
            ////取施工企业项目经理，如果有。
            var query = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid && p.bGrade == 15 && typeFlag.Contains(p.TypeFlag ?? "-99"));
            managers = query.ToList();
            if (managers.Count > 0)
            {
                result = "0," + managers[0].ID + ":" +
                    managers[0].ITypeFlag.ToString() + ":" +
                    managers[0].bGrade + ":" +
                    managers[0].CertificateLevel;
            }
            else
            {
                typeFlag = new string[] { "2", "40", "72" };////人员类型是项目总监
                ////取监理企业项目负责人，如果有，取等级最高的。
                managers = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid && p.bGrade == 42 && typeFlag.Contains(p.TypeFlag ?? "-99")).ToList();
                if (managers.Count > 0)
                {
                    int lvl = 0;
                    DTO.V_CheckXMFZR manager = null;
                    foreach (DTO.V_CheckXMFZR item in managers)
                    {
                        int ilvl = -1;
                        int.TryParse(item.CertificateLevel, out ilvl);
                        if (ilvl == -1 || (ilvl >= lvl && lvl > 0))
                        {
                            continue;
                        }
                        else
                        {
                            lvl = ilvl;
                            manager = item;
                        }
                    }
                    string Level = manager.CertificateLevel;
                    if (lvl == 0)
                    {
                        Level = "-1";
                        // result = "9,此人员（项目总监）尚未设置项目总监证书等级。";
                    }
                    result = "0," + manager.ID + ":" +
                           manager.ITypeFlag.ToString() + ":" +
                           manager.bGrade + ":" +
                           Level;
                }
                else
                {
                    result = "9,此人员可能存在以下问题：1.人员信息不存在或未审核通过 2.此人员没有项目负责人资格。";
                }
            }
            return JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 押证查询
        /// </summary>
        /// <param name="empId">ID或GUID</param>
        /// <param name="roleId">企业roleid</param>
        /// <returns></returns>
        public override string CheckXMFZR(string empId, string roleId, string areaCode)
        {
            string result = string.Empty;
            Guid empGuid = Guid.Empty;
            int empIntId = 0;
            if (string.IsNullOrEmpty(empId))
            {
                result = "9,参数不能为空.";
                return JsonConvert.SerializeObject(result);
            }
            ////值不为GUID
            if (!Guid.TryParse(empId, out empGuid))
            {
                if (int.TryParse(empId, out empIntId))
                {
                    empGuid = GetXMFZRQuery().Where(p => p.ID == empIntId).Select(p => p.EmpGuid).FirstOrDefault();
                    if (empGuid == Guid.Empty)
                    {
                        result = "9,人员empGuid不能为空.";
                        return JsonConvert.SerializeObject(result);
                    }
                }
                else
                {
                    result = "9,传入的参数格式不正确.";
                    return JsonConvert.SerializeObject(result);
                }
            }
            int bGrade = -1;
            if (!int.TryParse(roleId, out bGrade))
            {
                result = "9,传入的参数RoleId格式不正确.";
                return JsonConvert.SerializeObject(result);
            }
            ////按地区取得押证设置表数据
            var emp_ManagerCert = zbdlcontext.emp_ManagerCertCount.Where(e => e.RoleId == roleId && (e.IsDel == false || e.IsDel == null) && e.AreaCode == areaCode).OrderByDescending(e => e.SortCode);
            var TypeFlag = emp_ManagerCert.Select(m => m.TypeFlag).ToList();////押证人员类型
            IList<DTO.V_CheckXMFZR> managers = new List<DTO.V_CheckXMFZR>();
            ////取得人员信息
            managers = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid && p.bGrade == bGrade && TypeFlag.Contains(p.TypeFlag ?? "-99")).ToList();
            if (managers == null)
            {
                result = "9,此人员可能存在以下问题：1.人员信息不存在或未审核通过 2.此人员没有项目负责人资格。";
                return JsonConvert.SerializeObject(result);
            }
            var empTypeFlag = managers.Select(m => m.TypeFlag);////人员类型
            var CertLevel = managers.Select(m => m.CertificateLevel);////证书等级
            ////取得押证数量
            int CertCount = emp_ManagerCert.Where(e => empTypeFlag.Contains(e.TypeFlag) && (CertLevel.Contains(e.CertLevel) || e.CertLevel == "-99")).OrderByDescending(e => e.SortCode).Select(e => e.CertCount ?? 0).FirstOrDefault();
            if (CertCount > 0)
            {
                result = "0," + managers[0].ID + ":" + CertCount.ToString() + ":" + managers[0].EmpName;
            }
            else
            {
                result = "9,人员既不是监理企业项目总监也不是施工企业项目经理.";
            }
            return JsonConvert.SerializeObject(result);
        }

        ///// <summary>
        ///// 判断企业和项目经理是否临时锁定
        ///// </summary>
        ///// <param name="projectId"></param>
        ///// <param name="personId"></param>
        ///// <returns></returns>
        //public bool CheckTempLock(string areaCode, string objectId, int typeFlag)
        //{

        //    Zb_TempLock_Zbdl templock = zbdlcontext.ZbTempLock.Where(t => t.AreaCode == areaCode && t.ObjectId == objectId && t.TypeFlag == typeFlag).FirstOrDefault();
        //    if (templock != null && templock.IsLocked == true)
        //    {
        //        return true;
        //    }
        //    return false;
        //}
        ///// <summary>
        ///// 押证操作
        ///// </summary>
        ///// <param name="empId"></param>
        ///// <returns></returns>
        //public override bool EmpLockCertificate(
        //    string projectName,
        //    string ProjectKind,
        //    string CorpName,
        //    string xmjlName,
        //    string xmjlCode,
        //    string xmjlID,
        //    string areacode,
        //    string bidid,
        //    string zbkindclassid)
        //{
        //    int biaoduanid, kind, jingliid, classid;
        //    int.TryParse(bidid, out biaoduanid);
        //    int.TryParse(ProjectKind, out kind);
        //    int.TryParse(xmjlID, out jingliid);
        //    int.TryParse(zbkindclassid, out classid);
        //    //Zb_emp_LockCertificate empLock = new Zb_emp_LockCertificate
        //    //{
        //    //    areacode = areacode,
        //    //    bidid = biaoduanid,
        //    //    CorpName = CorpName,
        //    //    ProjectKind = kind,
        //    //    projectName = projectName,
        //    //    xmjlCode = xmjlCode,
        //    //    xmjlID = jingliid,
        //    //    xmjlName = xmjlName,
        //    //    zbkindclassid = classid,
        //    //    dateZB = DateTime.Now,
        //    //    editDate = DateTime.Now
        //    //};
        //    bool isLock = false;
        //    int lockCount = 0;////可押证数
        //    try
        //    {
        //        ////取得项目负责人可押证数
        //        IList<DTO.V_CheckXMFZR> managers = zbdlcontext.CheckXMFZR.Where(p => p.ID == jingliid).OrderByDescending(p => p.bGrade).ToList();
        //        foreach (DTO.V_CheckXMFZR m in managers)
        //        {
        //            if (m.bGrade == 15)////项目经理押一证
        //            {
        //                lockCount = 1;
        //                break;
        //            }
        //            if (m.bGrade == 42)////项目总监押三证
        //            {
        //                lockCount = 3;
        //                break;
        //            }
        //        }
        //        ////已押证数
        //        int listCount = zbdlcontext.LockCertificate.Where(p => p.xmjlID == jingliid && p.bstatus == "1").Count();
        //        if (lockCount <= listCount)
        //        {
        //            return false;
        //        }
        //        ////押证
        //        Zb_emp_LockCertificate empLock = new Zb_emp_LockCertificate
        //        {
        //            areacode = "",
        //            bidid = 0,
        //            CorpName = "",
        //            ProjectKind = 0,
        //            projectName = "",
        //            xmjlCode = "",
        //            xmjlID = jingliid,
        //            xmjlName = "",
        //            zbkindclassid = 0,
        //            dateZB = DateTime.Now,
        //            editDate = DateTime.Now,
        //            bstatus = "1"
        //        };
        //        zbdlcontext.LockCertificate.Add(empLock);
        //        zbdlcontext.SaveChanges();
        //        //IList<Zb_emp_LockCertificate> list = zbdlcontext.LockCertificate.Where(p => p.xmjlID == jingliid && p.bstatus == "99").ToList();
        //        //foreach (Zb_emp_LockCertificate i in list)
        //        //{
        //        //    i.bstatus = "0";
        //        //    i.editDate = DateTime.Now;
        //        //    zbdlcontext.SaveChanges();
        //        //}

        //        isLock = true;
        //    }
        //    catch (Exception ex)
        //    {

        //        SysLogManager.Log(new Sys_Log()
        //        {
        //            ErrorMessage = ex.Message,
        //            LogDate = DateTime.Now
        //        });
        //    }
        //    return isLock;
        //}

        ///// <summary>
        ///// 解证操作
        ///// </summary>
        ///// <param name="xmjlID"></param>
        ///// <param name="bidid"></param>
        ///// <returns></returns>
        //public override bool EmpUnlockCertificate(int xmjlID, int bidid, string areaCode)
        //{
        //    bool isUnLock = false;
        //    try
        //    {
        //        ////查询数据库
        //        Zb_emp_LockCertificate dbLockInfo = zbdlcontext.LockCertificate.Where(p => p.xmjlID == xmjlID && p.bstatus == "1").FirstOrDefault();
        //        ////修改赋值
        //        if (dbLockInfo != null)
        //        {
        //            dbLockInfo.bstatus = "0";
        //            dbLockInfo.editDate = DateTime.Now;
        //            zbdlcontext.SaveChanges();
        //        }

        //        isUnLock = true;
        //    }
        //    catch (Exception ex)
        //    {

        //        SysLogManager.Log(new Sys_Log()
        //        {
        //            ErrorMessage = ex.Message,
        //            LogDate = DateTime.Now
        //        });
        //    }

        //    return isUnLock;
        //}

        /// <summary>
        /// 获取能压证数量
        /// </summary>
        /// <param name="typeFlag">角色</param>
        /// <param name="bGrade">企业类型</param>
        /// <param name="level">级别</param>
        /// <returns>int</returns>
        private int CheckManagerRole(string typeFlag, int? bGrade, string level, string areaCode)
        {
            int canPledgeCounts = 0;
            if (typeFlag == "-1" && bGrade == 42)////监理企业项目总监
            {
                switch (level)
                {
                    case "1":
                        canPledgeCounts = 3;
                        break;
                    case "2":
                        canPledgeCounts = 2;
                        break;
                    case "3":
                        canPledgeCounts = 1;
                        break;
                }
            }
            else if (bGrade == 15)////施工企业项目经理
            {
                if (typeFlag == "0" || typeFlag == "-1")
                {
                    canPledgeCounts = 1;
                }
            }
            return canPledgeCounts;
        }
        #endregion 压证相关 无变动

        #region 人员相关 姜汉鑫更改
        /// <summary>
        /// 主管端
        /// </summary>
        /// <param name="typeFlag"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        //public override IList<tb_Emp_Manager_Zbdl> GetAdminEmployeeInfoList(string corpUserGuid)
        //{
        //    Guid cGuid = Guid.Empty;
        //    if (!Guid.TryParse(corpUserGuid, out cGuid))
        //    {
        //        return null;
        //    }
        //    var managers = zbdlcontext.Emp_Manager.Where(m => m.CorpUserGuid == cGuid && m.TypeFlag < 0).ToList();
        //    return managers;
        //}

        /// <summary>
        /// 根据corpUserGuid获取5大员列表
        /// </summary>
        /// <returns></returns>
        //public override IList<tb_Emp_Manager_Zbdl> GetEmployeeInfoList(string corpUserGuid)
        //{
        //    Guid cGuid = Guid.Empty;
        //    if (!Guid.TryParse(corpUserGuid, out cGuid))
        //    {
        //        return null;
        //    }
        //    IList<tb_Emp_Manager_Zbdl> managerlist = zbdlcontext.Emp_Manager.Where(m => m.CorpUserGuid == cGuid && m.TypeFlag > 0 &&
        //                                         (m.TypeFlag == 3 || m.TypeFlag == 4 || m.TypeFlag == 5 || m.TypeFlag == 7 || m.TypeFlag == 8 || m.TypeFlag == 9)).Distinct().ToList();
        //    return managerlist;
        //}

        /// <summary>
        /// 根据人员编号查询人员信息。
        /// </summary>
        /// <param name="userId">人员编号。</param>
        /// <returns></returns>
        public override string GetPersonInfo(string userId, string areaCode)
        {
            var model = new tb_Emp_Manager_Zbdl();
            try
            {
                if (!string.IsNullOrEmpty(userId))
                {
                    int iUserId = 0;
                    if (int.TryParse(userId, out iUserId))
                    {

                        model = zbdlcontext.Emp_Manager.Where(r => r.ID == iUserId).FirstOrDefault();
                    }
                    else
                    {
                        Guid gUserId = Guid.Empty;
                        if (Guid.TryParse(userId, out gUserId))
                        {
                            model = zbdlcontext.Emp_Manager.Where(r => r.EmpGuid == gUserId).FirstOrDefault();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return JsonConvert.SerializeObject(model);
        }
        #endregion 人员相关 姜汉鑫更改

        #region 获取人员资格证书相关 姜汉鑫更改

        /// <summary>
        /// 获取人员资格证书项集合。
        /// </summary>
        /// <param name="personType">人员类型。</param>
        /// <returns></returns>
        public override string GetPersonQualityItems(string personType, string areaCode)
        {

            return null;
        }

        /// <summary>
        /// 获取人员资格证书集合。
        /// </summary>
        /// <param name="userId">人员编号。</param>
        /// <returns></returns>
        public override string GetPersonQualities(string personId, string areaCode)
        {
            IList<Tb_Emp_TitleDetails_Zbdl> qualities = new List<Tb_Emp_TitleDetails_Zbdl>();

            Guid empGuid = Guid.Empty;
            Guid.TryParse(personId, out empGuid);
            try
            {
                qualities = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == empGuid).ToList();
            }
            catch
            {

            }

            return JsonConvert.SerializeObject(qualities);
        }

        /// <summary>
        /// 获取资格信息。
        /// </summary>
        /// <param name="qualityId">资格编号。</param>
        /// <returns></returns>
        public override string GetPersonQuality(string qualityId, string areaCode)
        {
            int qid = 0;
            int.TryParse(qualityId, out qid);
            Tb_Emp_TitleDetails_Zbdl quality = zbdlcontext.Emp_Qualities.SingleOrDefault(q => q.ID == qid);
            return JsonConvert.SerializeObject(quality);
        }
        /// <summary>
        /// 作者：毛凯
        /// 时间：2013-5-28
        /// 描述：zbdlry数据库中项目负责人安全生产考核B证
        /// </summary>
        /// <param name="personId"></param>
        /// <returns></returns>
        public override string GetPersonBQuality(string personId, string areaCode)
        {
            int pId = 0;
            Guid guid = Guid.Empty;
            if (int.TryParse(personId, out pId))
            {
                PersonDALWh pDal = new PersonDALWh();
                return JsonConvert.SerializeObject(pDal.GetPersonBQualityById(personId));
            }
            else if (Guid.TryParse(personId, out guid))
            {
                CMPersonSafeCert bc = zbdlcontext.BCards.Where(b => b.EmpGuid == guid && b.ValidTo != null && b.ValidTo > DateTime.Now).FirstOrDefault();
                return JsonConvert.SerializeObject(bc);
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion 获取人员资格证书相关 姜汉鑫更改

        #region 企业人员基本操作

        /// <summary>
        /// 按标识键查找人员信息
        /// </summary>
        /// <param name="userId">标识键</param>
        /// <returns></returns>
        public override string GetEmpManager(string userId, string areaCode)
        {
            var model = new tb_Emp_Manager();
            try
            {
                if (!string.IsNullOrEmpty(userId))
                {
                    int iUserId = 0;
                    if (int.TryParse(userId, out iUserId))
                    {
                        model = zbdlcontext.Emp_Manager.Where(r => r.ID == iUserId && (r.IsDel == false || r.IsDel == null)).Select(o =>
                            new tb_Emp_Manager()
                            {
                                #region 封装实体
                                EmpGuid = o.EmpGuid,
                                FlowCode = o.FlowCode,
                                AreaCode = o.AreaCode,
                                Birthday = o.Birthday,
                                BithdayMonth = o.BithdayMonth,
                                BithdayYear = o.BithdayYear,
                                ClassId = o.ClassId,
                                CorpClassID = o.CorpClassID,
                                CorpGuid = o.CorpGuid,
                                CorpID = o.CorpID,
                                CreatDate = o.CreatDate,
                                DogID = o.DogID,
                                DoMajor = o.DoMajor,
                                Duty = o.Duty,
                                DutyLevel = o.Duty,
                                Education = o.Education,
                                EMail = o.EMail,
                                empdogid = o.empdogid,
                                EmployeeType = o.EmployeeType,
                                GraduatedSchool = o.GraduatedSchool,
                                ID = o.ID,
                                IDCard = o.IDCard,
                                IDType = o.IDType,
                                InsuranceNum = o.InsuranceNum,
                                isFreeze = o.isFreeze,
                                IsLeave = o.IsLeave,
                                MobileTel = o.MobileTel,
                                Name = o.Name,
                                pwd = o.pwd,
                                Sex = o.Sex,
                                SpecialityID = o.SpecialityID,
                                Tel = o.Tel,
                                TypeFlag = o.TypeFlag,
                                ZhiWu = o.ZhiWu,
                                IfHaveCA = o.IfHaveCA,
                                isZZEmp = o.isZZEmp,
                                ICCard = o.ICCard
                                #endregion
                            }).FirstOrDefault();
                    }
                    else
                    {
                        Guid gUserId = Guid.Empty;
                        if (Guid.TryParse(userId, out gUserId))
                        {
                            model = zbdlcontext.Emp_Manager.Where(r => r.EmpGuid == gUserId
                            && (r.IsDel == false || r.IsDel == null)).Select(o =>
                            new tb_Emp_Manager()
                            {
                                #region 封装实体
                                EmpGuid = o.EmpGuid,
                                FlowCode = o.FlowCode,
                                AreaCode = o.AreaCode,
                                Birthday = o.Birthday,
                                BithdayMonth = o.BithdayMonth,
                                BithdayYear = o.BithdayYear,
                                ClassId = o.ClassId,
                                CorpClassID = o.CorpClassID,
                                CorpGuid = o.CorpGuid,
                                CorpID = o.CorpID,
                                CreatDate = o.CreatDate,
                                DogID = o.DogID,
                                DoMajor = o.DoMajor,
                                Duty = o.Duty,
                                DutyLevel = o.Duty,
                                Education = o.Education,
                                EMail = o.EMail,
                                empdogid = o.empdogid,
                                EmployeeType = o.EmployeeType,
                                GraduatedSchool = o.GraduatedSchool,
                                ID = o.ID,
                                IDCard = o.IDCard,
                                IDType = o.IDType,
                                InsuranceNum = o.InsuranceNum,
                                isFreeze = o.isFreeze,
                                IsLeave = o.IsLeave,
                                MobileTel = o.MobileTel,
                                Name = o.Name,
                                pwd = o.pwd,
                                Sex = o.Sex,
                                SpecialityID = o.SpecialityID,
                                Tel = o.Tel,
                                TypeFlag = o.TypeFlag,
                                ZhiWu = o.ZhiWu,
                                IfHaveCA = o.IfHaveCA,
                                isZZEmp = o.isZZEmp,
                                ICCard = o.ICCard
                                #endregion
                            }).FirstOrDefault();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return JsonConvert.SerializeObject(model);
        }

        /// <summary>
        /// 获取企业下的指定工人的证书列表
        /// </summary>
        /// <param name="empGuid">empGuid</param>
        /// <param name="condition">sql where</param>
        /// <returns></returns>
        public override string GetPersonTitleDetails(string empGuid, string condition, string areaCode)
        {
            var list = new List<Tb_Emp_TitleDetails_Zbdl>();
            try
            {
                if (!String.IsNullOrEmpty(empGuid))
                {
                    if (!StringHelper.SqlFilter(condition))
                    {
                        list = new PersonDALWh().GetPersonTitleDetails(empGuid, condition);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return JsonConvert.SerializeObject(list);
        }

        #region 人员信息私有方法
        /// <summary>
        /// 取得功能状态码
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="subClassID"></param>
        /// <returns></returns>
        private string GetPersonClassID(string CorpGuid, string subClassID, string areaCode)
        {
            Guid userGuid = Guid.Empty;
            if (!Guid.TryParse(CorpGuid, out userGuid))
            {
                return string.Empty;
            }
            string classIdStr = string.Empty;
            var corp = zbdlcontext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == userGuid).FirstOrDefault();
            if (corp != null)
            {
                int companyclassID = corp.classID ?? 0;////取得企业的功能状态码
                string classID = corp.classID.ToString();
                //取得配置表设置
                var list = zbdlcontext.T_Sys_CorpPsnMapping.Where(c => c.CorpClassId == classID).ToList();
                //配置信息不存在，取企业classid+10
                if (list.Count == 0 || list == null)
                {
                    if (companyclassID > 0)
                    {
                        return Convert.ToString(companyclassID + 10) + subClassID;////生成人员各项的状态码
                    }
                }
                //多条，按地区取值
                if (list.Count > 1)
                {
                    list = list.Where(c => c.AreaCode == areaCode).ToList();
                }
                if (list.FirstOrDefault() != null)
                {
                    classIdStr = list.FirstOrDefault().PsnClassId;
                    if (int.TryParse(classIdStr, out companyclassID))
                    {
                        return companyclassID.ToString() + subClassID;
                    }
                }

            }
            return string.Empty;
        }

        /// <summary>
        /// 验证当前登录用户取得用户信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckUserIsExist(string corpUserGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid corpGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out corpGuid))
            {
                result.Result = false;
                result.Message = "登录用户信息不正确！";
                return result;
            }
            var query = from user in zbdlcontext.T_Sys_Users
                        where user.UserGuid == corpGuid
                        select user;
            result.Result = true;
            result.ReturnValue = query.FirstOrDefault();
            return result;

        }

        /// <summary>
        /// 判断企业审核状态
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CheckCorpStasus(string corpUserGuid, string areaCode, int optType, string currentAreaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            try
            {
                Guid corpGuid = Guid.Empty;
                if (!Guid.TryParse(corpUserGuid, out corpGuid))
                {
                    result.Result = false;
                    result.Message = "企业信息不正确！";
                    return result;
                }
                ////取得企业信息
                var query = from corp in zbdlcontext.Corp_CompanyInfos
                            join user in zbdlcontext.T_Sys_Users on corp.CorpUserGuid equals user.UserGuid
                            where corp.CorpUserGuid == corpGuid && (corp.IsDel == false || corp.IsDel == null)
                            select new
                            {
                                classID = corp.classID,
                                roleID = user.RoleID,
                                corpName = corp.CorpName
                            };
                var corpInfo = query.SingleOrDefault();
                if (corpInfo == null)
                {
                    result.Result = false;
                    result.Message = "企业信息不存在！";
                    return result;
                }
                result = CheckFlowCode(corpUserGuid, optType, corpInfo.classID, corpInfo.roleID.ToString(), areaCode, currentAreaCode);
                if (!result.Result)
                {
                    result.Message = "所属企业 [" + corpInfo.corpName + "] 信息已上报审核，不能修改！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "人员信息验证失败" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 判断人员状态
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckEmpStasus(string empGuid, string areaCode, int optType, string currentAreaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            try
            {
                ////判断人员是否存在
                result = CheckEmpIsExist(empGuid);
                if (!result.Result)
                {
                    return result;
                }
                ////用户类型
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                int codeType = currentManager.ClassId ?? 0;
                if (codeType == 0)
                {
                    string classID = GetPersonClassID(currentManager.CorpGuid.ToString(), "", currentAreaCode);
                    int.TryParse(classID, out codeType);
                }
                ////用户判断
                DTO.OperationResult result0 = CheckUserIsExist(currentManager.CorpGuid.ToString());
                if (!result0.Result || result0.ReturnValue == null)
                {
                    result.Result = false;
                    result.Message = "登录用户信息有误！";
                    return result;
                }
                var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
                int? roleId = userInfo.RoleID;
                ////判断人员是否上报审核
                result = CheckFlowCode(empGuid, optType, codeType, roleId.ToString(), areaCode, currentAreaCode);
                if (!result.Result)
                {
                    result.Message = "人员 [" + currentManager.Name + "] 已上报审核，不能执行此操作！";
                }
                result.ReturnValue = currentManager;
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "人员信息验证失败" + ex.Message;
                result.Result = false;
            }
            return result;
        }
        /// <summary>
        /// 取得审核状态及操作权限
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="optType"></param>
        /// <param name="currentManager"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckFlowCode(string empGuid,
            int optType,
            int? codeType,
            string roleId,
            string areaCode,
            string currentAreaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            List<Tb_FlowCode_Zbdl> flowCodes = new List<Tb_FlowCode_Zbdl>();
            ////取得当前审核状态
            var query = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid.Trim() && f.CodeType == codeType && f.IsDel == false);
            if (!string.IsNullOrEmpty(areaCode))
            {
                query = query.Where(f => f.AreaCode == areaCode);
            }
            if ("06" == System.Configuration.ConfigurationManager.AppSettings["Area"])
            {
                int appid = 97;
                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                query = query.Where(f => f.AppID == appid);
            }

            flowCodes = query.ToList();
            if (flowCodes == null || flowCodes.Count == 0)
            {
                if (string.IsNullOrEmpty(currentAreaCode))
                {
                    result.Result = false;
                    result.Message = "您不能对此信息进行修改！";
                    return result;
                }
                ////添加审核状态
                Tb_FlowCode_Zbdl flowCode = EmpFlowCode(empGuid, codeType, currentAreaCode);
                flowCodes.Add(flowCode);
            }
            OptType opt = (OptType)System.Enum.Parse(typeof(OptType), optType.ToString());////当前操作
            ////返回flowcode状态
            foreach (Tb_FlowCode_Zbdl flowCode in flowCodes)
            {
                var result1 = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                    roleId, string.Empty,
                                    flowCode.AreaCode,
                                    flowCode.CodeType.ToString(), flowCode.FlowCode, opt);
                result.Result = result1.Result;
                result.Message = result1.Message;
                result.ReturnValue = result1.NextFlowCode;
                if (!result.Result)
                {
                    break;
                }
            }
            return result;
        }
        /// <summary>
        /// 只查询tb_flowcode中存在项的审核状态-用于证书审核状态判断
        /// </summary>
        /// <param name="objGuid"></param>
        /// <param name="optType"></param>
        /// <param name="codeType"></param>
        /// <param name="currentManager"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckSubFlowCode(string objGuid, int optType, int? codeType, string corpUserGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            //////用户判断
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result || result0.ReturnValue == null)
            {
                result.Result = false;
                result.Message = "登录用户信息有误！";
                return result;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            string roleId = userInfo.RoleID.ToString();

            return CheckFlowCode(objGuid, optType, codeType, roleId, string.Empty, string.Empty);
        }

        /// <summary>
        /// 取得审核状态对应的文字显示
        /// </summary>
        /// <param name="flowCode"></param>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private string GetFlowCodeTitle(string flowCode, string classId, string areaCode)
        {
            string strFlowCode = string.Empty;
            if (!string.IsNullOrEmpty(flowCode))
            {
                strFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                   areaCode, classId, flowCode);
            }
            return strFlowCode;
        }
        /// <summary>
        /// 人员基本信息添加
        /// </summary>
        /// <param name="corpGuid"></param>
        /// <param name="emp"></param>
        /// <param name="isReturnModel"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpManagerInfoAdd(
            DTO.tb_Emp_Manager emp,
            bool isReturnModel,
            string areaCode,
            string classID,
            string companyAreaCode,
            T_Sys_Users_Zbdl userInfo)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            //默认数据赋值
            int codeType = 0;
            int.TryParse(classID, out codeType);
            emp.CorpGuid = userInfo.UserGuid;
            emp.CorpClassID = userInfo.RoleID;
            emp.ClassId = codeType;
            emp.FlowCode = "0";
            emp.IsDel = false;
            emp.corpName = userInfo.Name;
            emp.AreaCode = companyAreaCode;
            if (emp.Birthday != null)
            {
                DateTime dt = DateTime.Parse(emp.Birthday.ToString());
                emp.BithdayYear = dt.Year;
                emp.BithdayMonth = dt.Month;
            }
            emp.CreatDate = DateTime.Now;
            emp.DogID = userInfo.DogID;
            ////添加人员基本信息
            tb_Emp_Manager_Zbdl emp_E = new tb_Emp_Manager_Zbdl();
            EntityHelper.ConvertEntity2OtherEntity(emp, emp_E);
            tb_Emp_Manager_Zbdl manager = zbdlcontext.Emp_Manager.Add(emp_E);
            zbdlcontext.SaveChanges();
            result.Message = "人员基本信息添加成功！";
            ////日志
            var flag = SetUserLog("添加人员基本信息", manager, "01", "1", areaCode, manager.CorpGuid.ToString());
            if (!flag)
            {
                result.Result = false;
                result.Message = "日志写入出错！";
                return result;
            }
            if (isReturnModel)
            {
                result.ReturnValue = manager;
            }
            return result;
        }

        /// <summary>
        /// 修改人员基本信息
        /// </summary>
        /// <param name="currentManager"></param>
        /// <param name="emps"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpManagerInfoEdit(tb_Emp_Manager_Zbdl currentManager, DTO.tb_Emp_Manager emps, string areaCode)
        {
            tb_Emp_Manager_Zbdl dbEmp = new tb_Emp_Manager_Zbdl();
            EntityHelper.ConvertEntity2OtherEntity(emps, dbEmp);
            EmpManagerTypeFlag(currentManager.CorpGuid, currentManager.EmpGuid, emps.TypeFlag.Trim());
            //人员类型
            string TypeFlag = currentManager.TypeFlag;
            if (TypeFlag.Split(',').Contains(emps.TypeFlag))
            {
                dbEmp.TypeFlag = currentManager.TypeFlag;
            }
            else
            {
                dbEmp.TypeFlag = currentManager.TypeFlag + "," + dbEmp.TypeFlag;
            }
            EntityHelper.ConvertEntity2Entity<tb_Emp_Manager_Zbdl>(dbEmp, currentManager);

            ////保存工作地址
            var corp = zbdlcontext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == dbEmp.CorpGuid).FirstOrDefault();
            if (corp != null)
            {
                corp.CorpName = emps.corpName;
            }

            zbdlcontext.SaveChanges();
            DTO.OperationResult result = new DTO.OperationResult();
            result.Message = "修改人员基本信息成功！";
            result.Result = true;
            ////日志
            var flag = SetUserLog("修改人员基本信息", currentManager, "01", "2", areaCode, currentManager.CorpGuid.ToString());
            if (!flag)
            {
                result.Result = false;
                result.Message = "日志写入出错！";
                return result;
            }
            return result;
        }


        /// <summary>
        /// 添加flowcode
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="codeType"></param>
        /// <param name="areaCode"></param>
        private Tb_FlowCode_Zbdl EmpFlowCode(string empGuid, int? codeTypeInt, string areaCode)
        {
            ////codeTypeInt为null时，通过企业的classid获取人员的codetype
            string flowCodeType = string.Empty;
            int codeType = 0;
            if (codeTypeInt == null || codeTypeInt.ToString().Length < 2)
            {
                var result = CheckEmpIsExist(empGuid);
                if (!result.Result)
                {
                    return null;
                }
                tb_Emp_Manager_Zbdl emp = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                flowCodeType = GetPersonClassID(emp.CorpGuid.ToString(), "", areaCode);
                int.TryParse(flowCodeType.Trim(), out codeType);
            }
            else
            {
                codeType = (int)codeTypeInt;
            }
            int appid = 0;
            string appidStr = System.Configuration.ConfigurationManager.AppSettings["AppID"];
            int.TryParse(appidStr, out appid);

            Tb_FlowCode_Zbdl flowCode = null;
            if (System.Configuration.ConfigurationManager.AppSettings["Area"] == "06")
            {
                ////添加flowCode
                flowCode = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid.Trim() && f.CodeType == codeType && f.AreaCode == areaCode && f.IsDel == false && f.AppID == 97).FirstOrDefault();
            }
            else
            {
                flowCode = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid.Trim() && f.CodeType == codeType && f.AreaCode == areaCode && f.IsDel == false).FirstOrDefault();
            }

            if (flowCode != null)
            {
                return flowCode;
            }
            flowCode = new Tb_FlowCode_Zbdl();
            flowCode.AreaCode = areaCode;
            flowCode.CodeType = codeType;
            flowCode.FlowCode = "0";
            flowCode.IsDel = false;
            flowCode.ObjectId = empGuid;
            flowCode.UpdateTime = DateTime.Now;


            if (System.Configuration.ConfigurationManager.AppSettings["Area"] == "06")
            {
                flowCode.AppID = appid;
            }
            zbdlcontext.FlowCodes.Add(flowCode);
            zbdlcontext.SaveChanges();
            return flowCode;
        }
        /// <summary>
        /// 人员上报-修改审核状态
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="codeType"></param>
        /// <param name="areaCode"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpFlowCodeEdit(string empGuid, int? codeType, string areaCode, string code, string description)
        {
            DTO.OperationResult result = new OperationResult();
            Tb_FlowCode_Zbdl flowCode = EmpFlowCode(empGuid, codeType, areaCode);
            flowCode.FlowCode = code;
            flowCode.UpdateTime = DateTime.Now;
            flowCode.Description = description;
            zbdlcontext.SaveChanges();
            result.Result = true;
            //result.Message = message+"成功！";
            return result;
        }

        /// <summary>
        /// 取消管理人员人员职务
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="typeFlag"></param>
        private void EmpManagerTypeFlag(Guid? corpUserGuid, Guid empGuid, string typeFlag)
        {
            if (typeFlag == "-1")
            {
                return;
            }
            var emps = zbdlcontext.Emp_Manager.Where(e => e.CorpGuid == corpUserGuid && e.EmpGuid != empGuid && e.TypeFlag.Contains(typeFlag) && (e.IsDel == false || e.IsDel == null)).ToList();
            if (emps != null && emps.Count() > 0)
            {
                foreach (tb_Emp_Manager_Zbdl emp in emps)
                {
                    string tFlag = emp.TypeFlag.Trim() + ",";
                    emp.TypeFlag = tFlag.Replace(typeFlag.Trim() + ",", "").TrimEnd(',');
                    if (emp.TypeFlag.Length == 0)
                    {
                        emp.TypeFlag = "-1";//普通人员
                    }
                    zbdlcontext.SaveChanges();
                }
            }
        }

        /// <summary>
        /// 修改人员FlowCode
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="typeFlag"></param>
        private void EmpFlowCodeEdit(Guid empGuid, string flowCode)
        {
            var emp = zbdlcontext.Emp_Manager.Where(e => e.EmpGuid == empGuid && (e.IsDel == false || e.IsDel == null)).FirstOrDefault();
            if (emp != null)
            {
                emp.FlowCode = flowCode;
                zbdlcontext.SaveChanges();
            }
        }
        #endregion

        #region 人员基本信息 添加、修改、删除

        /// <summary>
        /// 判断人员是否存在
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult CheckEmpIsExist(string empGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "人员信息不正确！";
                return result;
            }
            ////查询人员
            tb_Emp_Manager_Zbdl currentManager = zbdlcontext.Emp_Manager.Where(m => (m.IsDel == false || m.IsDel == null) && m.EmpGuid == eGuid).FirstOrDefault();
            if (currentManager == null)
            {
                result.Result = false;
                result.Message = "人员信息不存在！";
                return result;
            }
            result.Result = true;
            result.ReturnValue = currentManager;
            return result;
        }

        /// <summary>
        /// 查询身份证号是否存在
        /// </summary>
        /// <param name="idCard"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult IDCardIsExists(string idCard, string corpUserGuid, string empGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid corpGuid = Guid.Empty;
                Guid eGuid = Guid.Empty;
                if (!Guid.TryParse(corpUserGuid, out corpGuid))
                {
                    result.Message = "企业GUID不正确！";
                    result.Result = false;
                    return result;
                }
                if (!Guid.TryParse(empGuid, out eGuid))
                {
                    result.Message = "人员GUID不正确！";
                    result.Result = false;
                    return result;
                }
                ////判断身份证号是否合法
                if (!PersonIDCardValid.CheckIDCard(idCard.Trim()))
                {
                    result.Message = "身份证号不合法！";
                    result.Result = false;
                    return result;
                }
                ////判断身份证是否存在
                var query = from emp in zbdlcontext.Emp_Manager
                            where emp.IDCard == idCard.Trim() && emp.CorpGuid == corpGuid && emp.EmpGuid != eGuid && (emp.IsDel == false || emp.IsDel == null)
                            select new
                            {
                                emp.EmpGuid,
                                emp.Name
                            };
                if (query.Count() > 0)
                {
                    result.Message = string.Format("您所输入的身份证号[{0}]重复，与[{1}]具有相同的身份证号。", idCard.Trim(), query.FirstOrDefault().Name);
                    result.ReturnValue = query.FirstOrDefault().EmpGuid + "," + query.FirstOrDefault().Name;
                    result.Result = false;
                    return result;
                }
            }
            catch
            { }
            result.Result = true;
            return result;
        }

        /// <summary>
        /// 查询身份证号是否存在
        /// </summary>
        /// <param name="idCard"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        private  DTO.OperationResult IDCardIsExists(string idCard, string empGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid eGuid = Guid.Empty;
                if (!Guid.TryParse(empGuid, out eGuid))
                {
                    result.Message = "人员GUID不正确！";
                    result.Result = false;
                    return result;
                }
                ////判断身份证号是否合法
                if (!PersonIDCardValid.CheckIDCard(idCard.Trim()))
                {
                    result.Message = "身份证号不合法！";
                    result.Result = false;
                    return result;
                }
                ////判断身份证是否存在
                var query = from emp in zbdlcontext.Emp_Manager
                            where emp.IDCard == idCard.Trim() && emp.EmpGuid != eGuid && (emp.IsDel == false || emp.IsDel == null)
                            select new
                            {
                                emp.EmpGuid,
                                emp.Name
                            };
                if (query.Count() > 0)
                {
                    result.Message = string.Format("您所输入的身份证号[{0}]重复，与[{1}]具有相同的身份证号。", idCard.Trim(), query.FirstOrDefault().Name);
                    result.ReturnValue = query.FirstOrDefault().EmpGuid + "," + query.FirstOrDefault().Name;
                    result.Result = false;
                    return result;
                }
            }
            catch
            { }
            result.Result = true;
            return result;
        }


        /// <summary>
        /// 企业添加人员信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emp"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpPersonInfoAdd(string corpUserGuid,
            DTO.tb_Emp_Manager emp,
            IList<DTO.Tb_Emp_TitleDetailsExt> empQualities,
            IList<DTO.Tb_Emp_Post> empPosts,
            bool isReturnModel,
            string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            #region 数据校验
            if (emp == null)
            {
                result.Result = false;
                result.Message = "人员信息不存在！";
                return result;
            }
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result || result0.ReturnValue == null)
            {
                result.Result = false;
                result.Message = "登录用户信息有误！";
                return result;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            if (emp.EmpGuid == Guid.Empty)
            {
                emp.EmpGuid = Guid.NewGuid();
            }
            ////判断身份证
            if (emp.IDType == "1")
            {
                ////判断身份证
                result = IDCardIsExists(emp.IDCard, corpUserGuid, emp.EmpGuid.ToString());
                if (!result.Result)
                {
                    return result;
                }
                result = IDCardIsExists(emp.IDCard, emp.EmpGuid.ToString());
                if (!result.Result)
                {
                    emp.EmployeeType = "100";
                    emp.Remark = result.Message;
                }
            }
            ////如果是管理人员，检验企业审核状态。
            if (emp.TypeFlag.Trim() != "-1")
            {
                ////管理人员判断状态进行修改 2013-10-19 毛凯
                //result = CheckCorpStasus(corpUserGuid, string.Empty, 1, areaCode);
                result = CheckManagerStatus(corpUserGuid, emp.TypeFlag, emp.EmpGuid.ToString(), 1, areaCode);
                if (!result.Result)
                {
                    return result;
                }
            }
            #endregion
            string classID = GetPersonClassID(corpUserGuid, "", areaCode);
            string CompanyAreaCode = zbdlcontext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == userInfo.UserGuid && (c.IsDel == false || c.IsDel == null)).Select(c => c.AreaCode).FirstOrDefault();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    EmpManagerTypeFlag(userInfo.UserGuid, emp.EmpGuid, emp.TypeFlag.Trim());
                    ////添加人员基本信息
                    result = EmpManagerInfoAdd(emp, true, areaCode, classID, CompanyAreaCode, userInfo);
                    ////添加FlowCode
                    EmpFlowCode(emp.EmpGuid.ToString(), emp.ClassId, areaCode);
                    tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                    ////添加人员职称信息
                    if (empPosts != null)
                    {
                        var result1 = EmpPostsModif(corpUserGuid, currentManager, empPosts, areaCode);
                        result.Result = result1.Result;
                        result.Message += result1.Message;
                    }
                    ////添加人员安全考核证
                    if (empQualities != null)
                    {
                        var result2 = EmpTitleDetailsExtModif(corpUserGuid, currentManager, empQualities, areaCode);
                        result.Result = result2.Result;
                        result.Message += result2.Message;
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员基本信息添加失败" + ex.InnerException;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 企业修改人员信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpPersonInfoEdit(string corpUserGuid,
            DTO.tb_Emp_Manager emps,
            IList<DTO.Tb_Emp_TitleDetailsExt> empQualities,
            IList<DTO.Tb_Emp_Post> empPosts,
            string areaCode)
        {
            ////判断人员状态
            DTO.OperationResult result0 = CheckEmpStasus(emps.EmpGuid.ToString(), string.Empty, 1, areaCode);
            if (!result0.Result)
            {
                return result0;
            }
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            ////判断身份证
            if (emps.IDType == "1")
            {
                result = IDCardIsExists(emps.IDCard, corpUserGuid, emps.EmpGuid.ToString());
                if (!result.Result)
                {
                    return result;
                }
                result = IDCardIsExists(emps.IDCard, emps.EmpGuid.ToString());
                if (!result.Result)
                {
                    emps.EmployeeType = "100";
                    emps.Remark = result.Message;
                }
            }
            ////如果是管理人员，检验企业审核状态。
            if (emps.TypeFlag.Trim() != "-1")
            {
                ////管理人员判断状态进行修改 2013-10-19 毛凯
                result = CheckManagerStatus(corpUserGuid, emps.TypeFlag, emps.EmpGuid.ToString(), 1, areaCode);
                //result = CheckCorpStasus(corpUserGuid, string.Empty, 1, areaCode);
                if (!result.Result)
                {
                    return result;
                }
            }
            using (DbConnection con = ((IObjectContextAdapter)zbdlcontext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////修改人员基本信息
                    tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result0.ReturnValue;
                    result = EmpManagerInfoEdit(currentManager, emps, areaCode);
                    ////修改人员职称信息
                    if (empPosts != null)
                    {
                        var result1 = EmpPostsModif(corpUserGuid, currentManager, empPosts, areaCode);
                        result.Result = result1.Result;
                        result.Message += result1.Message;
                    }
                    ////修改人员安全考核证
                    if (empQualities != null)
                    {
                        var result2 = EmpTitleDetailsExtModif(corpUserGuid, currentManager, empQualities, areaCode);
                        result.Result = result2.Result;
                        result.Message += result2.Message;
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改人员基本信息失败：" + ex.Message;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 取消人员为管理人员
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoEditTypeFlag(string empGuid, string typeFlag, string areaCode)
        {
            ////判断人员是否存在
            DTO.OperationResult result0 = CheckEmpIsExist(empGuid);
            if (!result0.Result)
            {
                return result0;
            }
            tb_Emp_Manager_Zbdl dbEmp = (tb_Emp_Manager_Zbdl)result0.ReturnValue;
            ////管理人员状态修改
            DTO.OperationResult result = CheckManagerStatus(dbEmp.CorpGuid.ToString(), typeFlag, empGuid, 1, areaCode);
            if (!result.Result)
            {
                return result;
            }
            try
            {
                ////修改人员职务
                string tFlag = dbEmp.TypeFlag;
                if (tFlag.Split(',').Contains(typeFlag.Trim()))
                {
                    tFlag = dbEmp.TypeFlag.Trim() + ",";
                    dbEmp.TypeFlag = tFlag.Replace(typeFlag.Trim() + ",", "").TrimEnd(',');
                    if (dbEmp.TypeFlag.Length == 0)
                    {
                        dbEmp.TypeFlag = "-1";//普通人员
                    }
                }
                zbdlcontext.SaveChanges();
                result.Message = "取消人员为管理人员成功！";
                result.Result = true;
                ////日志
                var flag = SetUserLog("取消人员为管理人员", dbEmp, "01", "2", areaCode, dbEmp.CorpGuid.ToString());
                if (!flag)
                {
                    result.Result = false;
                    result.Message = "日志写入出错！";
                    return result;
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "取消人员为管理人员失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 通过身份证导入人员
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoAddTypeFlag(string empGuid, string typeFlag, string areaCode)
        {
            string msg = "从业人员";
            if (typeFlag != "-1")
            {
                msg = "管理人员";
            }
            DTO.OperationResult result = new OperationResult();
            result.Result = true;
            result.Message = "";
            try
            {
                ////判断人员是否存在
                DTO.OperationResult result0 = CheckEmpIsExist(empGuid);
                if (!result0.Result)
                {
                    return result0;
                }
                tb_Emp_Manager_Zbdl dbEmp = (tb_Emp_Manager_Zbdl)result0.ReturnValue;
                ////修改人员职务
                string tFlag = dbEmp.TypeFlag;
                if (tFlag.Split(',').Contains(typeFlag.Trim()))
                {
                    if (typeFlag.Trim() != "-1")
                    {
                        result.Message = "人员已经是" + msg + "了，不需要再重复添加信息了！";
                    }
                    else
                    {
                        result.Message = "导入人员成功！";
                    }
                    result.Result = true;
                    return result;
                }
                ////管理人员状态判断修改
                result = CheckManagerStatus(dbEmp.CorpGuid.ToString(), typeFlag, empGuid, 1, areaCode);
                if (!result.Result)
                {
                    return result;
                }
                EmpManagerTypeFlag(dbEmp.CorpGuid, dbEmp.EmpGuid, typeFlag.Trim());
                dbEmp.TypeFlag = tFlag + "," + typeFlag;
                zbdlcontext.SaveChanges();
                //添加审核状态
                EmpFlowCode(dbEmp.EmpGuid.ToString(), dbEmp.ClassId, areaCode);
                result.Message = "导入" + msg + "成功！";
                result.Result = true;
                ////日志
                var flag = SetUserLog("导入" + msg, dbEmp, "01", "5", areaCode, dbEmp.CorpGuid.ToString());
                if (!flag)
                {
                    result.Result = false;
                    result.Message = "日志写入出错！";
                    return result;
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "取消人员职务失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 删除人员信息
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoDel(IList<string> empGuids, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            string managerNm = string.Empty;
            List<tb_Emp_Manager_Zbdl> emps = new List<tb_Emp_Manager_Zbdl>();
            foreach (var item in empGuids)
            {
                ////判断人员状态
                DTO.OperationResult result1 = CheckEmpStasus(item.Trim(), string.Empty, 2, areaCode);
                if (!result1.Result)
                {
                    result.Result = false;
                    result.Message += result1.Message;
                    result1.ReturnValue = null;
                    continue;
                }
                var manager = (tb_Emp_Manager_Zbdl)result1.ReturnValue;
                ////如果有管理人员，先解除管理人员职务再删除。
                if (manager.TypeFlag.Trim() != "-1")
                {
                    managerNm += manager.Name + ",";
                    continue;
                }
                emps.Add(manager);
            }
            if (!string.IsNullOrEmpty(managerNm))
            {
                result.Result = false;
                result.Message = "人员[" + managerNm.TrimEnd(',') + "]是管理人员，必须先取消人员的管理人员身份才能删除！";
                result.ReturnValue = null;
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)zbdlcontext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var item in emps)
                    {
                        ////删除职称
                        EmpPostsDel(item.EmpGuid.ToString(), areaCode);
                        ////删除安全考核证
                        EmpTitleDetailsExtDel(item.EmpGuid.ToString(), areaCode);
                        ////删除资质 tb_Emp_TitleDetails
                        EmpQualitysDel(item.EmpGuid.ToString(), areaCode);
                        ////删除工作经历 tb_WorkExperience
                        WorkExperiencesDel(item.EmpGuid.ToString(), areaCode);
                        ////删除人员信息
                        tb_Emp_Manager_Zbdl dbEmp = item;
                        dbEmp.IsDel = true;
                        zbdlcontext.SaveChanges();
                        result.Message += "删除人员" + dbEmp.Name + "成功！";
                        ////2.日志
                        var flag = SetUserLog("删除人员信息", dbEmp, "", "3", areaCode, dbEmp.CorpGuid.ToString());
                        if (!flag)
                        {
                            result.Result = false;
                            result.Message = "日志写入出错！";
                            return result;
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员删除失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        #endregion

        #region  人员列表查询
        /// <summary>
        /// 取得人员Flowcode
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="typeFlag"></param>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private string GetManagerFlowCode(tb_Emp_Manager emp_D, string areaCode)
        {
            string empGuid = emp_D.EmpGuid.ToString();
            if (emp_D.TypeFlag != "-1")
            {
                ////先判断该人员在tb_FlowCode表中是否存在记录，存在则判断在当前地区是否存在记录，否则则认为可操作
                var flowCodes = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid && f.CodeType == emp_D.ClassId && (f.IsDel == false || f.IsDel == null)).ToList();
                if (flowCodes == null || flowCodes.Count <= 0)
                {
                    return "0";
                }
                //string flowCode = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid && f.CodeType == emp_D.ClassId && (f.IsDel == false || f.IsDel == null) && f.AreaCode.StartsWith(areaCode)).Select(f => f.FlowCode).FirstOrDefault();
                if (emp_D.FlowCode == null)
                {
                    return "1,";
                }
                var corpUserGuid = emp_D.CorpGuid.ToString();
                var currentMarketCorpFlow = zbdlcontext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.AreaCode == areaCode && (f.IsDel == false || f.IsDel == null)).FirstOrDefault();
                return currentMarketCorpFlow == null ? null : currentMarketCorpFlow.FlowCode;
            }//end
            return null;
            // return flowCode;
        }
        /// <summary>
        /// 取得所有管理人员及人员详细信息页
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetEmpManagersAllList(int pageCount, int pageSize, string conditions, string areaCode)
        {
            var query = zbdlcontext.Emp_Manager.Where(p => (p.IsDel == false || p.IsDel == null));
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager_Zbdl>(condition);
            }
            List<tb_Emp_Manager_Zbdl> emps = null;
            if (pageSize > 0)
            {
                emps = query.OrderByDescending(q => q.ID).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                emps = query.OrderByDescending(q => q.ID).ToList();
            }
            var emplist = new List<DTO.tb_Emp_Manager>();
            string empGuid = string.Empty;
            foreach (var emp in emps)
            {
                DTO.tb_Emp_Manager emp_D = new DTO.tb_Emp_Manager();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(emp, emp_D);
                empGuid = emp_D.EmpGuid.ToString();

                string flowCode = string.Empty;

                int appid = 0;
                string appidStr = System.Configuration.ConfigurationManager.AppSettings["AppID"];
                int.TryParse(appidStr, out appid);

                if (System.Configuration.ConfigurationManager.AppSettings["Area"] == "06")
                {
                    flowCode = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid && f.CodeType == emp.ClassId && (f.IsDel == false || f.IsDel == null) && f.AreaCode == areaCode && f.AppID == appid).Select(f => f.FlowCode).FirstOrDefault();
                }
                else
                    flowCode = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid && f.CodeType == emp.ClassId && (f.IsDel == false || f.IsDel == null) && f.AreaCode == areaCode).Select(f => f.FlowCode).FirstOrDefault();

                emp_D.FlowCode = flowCode;
                emp_D.StrFlowCode = GetFlowCodeTitle(
                       flowCode,
                        emp_D.ClassId.ToString(), areaCode);
                //取得管理人员FlowCode
                emp_D.CorpFlowCode = GetManagerFlowCode(emp_D, areaCode);
                var corp = zbdlcontext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == emp_D.CorpGuid).FirstOrDefault();
                if (corp != null)
                {
                    emp_D.corpName = corp.CorpName;
                }
                emplist.Add(emp_D);
            }
            return emplist;
        }
        /// <summary>
        /// 取得所有满足条件的人员数目
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetEmpManagersAllCount(string conditions, string areaCode)
        {
            var query = zbdlcontext.Emp_Manager.Where(p => (p.IsDel == false || p.IsDel == null));
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager_Zbdl>(condition);
            }

            return query.Count();
        }
        /// <summary>
        /// 取得人员列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetEmpManagersList(int pageCount, int pageSize, string conditions, string areaCode)
        {
            return GetEmpManagerOtherList(pageCount, pageSize, conditions, string.Empty, areaCode);
        }

        /// <summary>
        /// 返回人员列表数目
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetEmpManagerListCount(string conditions, string areaCode)
        {
            return GetEmpManagerOtherListCount(conditions, string.Empty, areaCode);
        }

        /// <summary>
        /// 取得其他人员列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetEmpManagerOtherList(int pageCount, int pageSize, string conditions, string certList, string areaCode)
        {
            ////1.查询满足条件的用户guid。
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            //var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on new
                        {
                            EmpGuid = emps.EmpGuid,
                            IsDel = (bool?)false
                        } equals new
                        {
                            EmpGuid = post.EmpGuid,
                            IsDel = post.IsDel
                        }
                        into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on new
                        {
                            EmpGuid = (Guid?)emps.EmpGuid,
                            IsDel = (bool?)false
                        }
                        equals new
                        {
                            EmpGuid = title.EmpGuid,
                            IsDel = title.IsDel
                        }
                        into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            Post_Corp = posts.Post_Corp,
                            Post_Major = posts.Post_Major,
                            Post_psDate = posts.Post_psDate,
                            Post_psOrg = posts.Post_psOrg,
                            Post_psZG = posts.Post_psZG,
                            Post_psZGCode = posts.Post_psZGCode,
                            PostId = posts.Id,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            StampCode = titles.StampCode,
                            IfHaveCA = emps.IfHaveCA,
                            isZZEmp = emps.isZZEmp,
                            AppID = emps.AppID,
                            ICCard = emps.ICCard
                            #endregion
                        };
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            //其他人员验证
            var guidEmp = new List<Guid>();
            if (!string.IsNullOrEmpty(certList))
            {
                var list = JsonConvert.DeserializeObject<List<int>>(certList);
                guidEmp = query.Where(q => list.Contains(q.TypeFlags ?? -1)).Select(q => q.EmpGuid).ToList().Distinct().ToList();
                query = query.Where(q => !list.Contains(q.TypeFlags ?? -1));
            }//end
            var empGuids = new List<Guid>();
            empGuids = query.Select(q => q.EmpGuid).ToList();
            //过滤多证重复人员
            if (guidEmp != null && guidEmp.Count > 0)
            {
                empGuids = empGuids.Where(e => !guidEmp.Contains(e)).ToList();
            }//end

            if (pageSize > 0)
            {
                empGuids = empGuids.Distinct().OrderBy(e => e).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                empGuids = empGuids.Distinct().ToList();
            }
            ////2.查询人员信息。
            var query1 = from emps in dbEmp
                         join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                         join post in dbEmpPost on new
                         {
                             EmpGuid = emps.EmpGuid,
                             IsDel = (bool?)false
                         } equals new
                         {
                             EmpGuid = post.EmpGuid,
                             IsDel = post.IsDel
                         } into jPosts
                         from posts in jPosts.DefaultIfEmpty()
                         join title in dbTitles on new
                         {
                             EmpGuid = (Guid?)emps.EmpGuid,
                             IsDel = (bool?)false
                         }
                         equals new
                         {
                             EmpGuid = title.EmpGuid,
                             IsDel = title.IsDel
                         } into jTitles
                         from titles in jTitles.DefaultIfEmpty()
                         where emps.FlowAreaCode == areaCode && empGuids.Contains(emps.EmpGuid) && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                         select new tb_Emp_Manager()
                         {
                             #region 封装实体

                             EmpGuid = emps.EmpGuid,
                             AreaCode = emps.AreaCode,
                             FlowCode = emps.RealFlowCode,
                             corpName = companies.CorpName,
                             Birthday = emps.Birthday,
                             BithdayMonth = emps.BithdayMonth,
                             BithdayYear = emps.BithdayYear,
                             ClassId = emps.ClassId,
                             CorpClassID = emps.CorpClassID,
                             CorpGuid = emps.CorpGuid,
                             CorpID = emps.CorpID,
                             CreatDate = emps.CreatDate,
                             DogID = emps.DogID,
                             DoMajor = emps.DoMajor,
                             Duty = emps.Duty,
                             DutyLevel = emps.Duty,
                             Education = emps.Education,
                             EMail = emps.EMail,
                             empdogid = emps.empdogid,
                             EmployeeType = emps.EmployeeType,
                             GraduatedSchool = emps.GraduatedSchool,
                             ID = emps.ID,
                             IDCard = emps.IDCard,
                             IDType = emps.IDType,
                             InsuranceNum = emps.InsuranceNum,
                             //InsutanceCode=emps.
                             isFreeze = emps.isFreeze,
                             IsLeave = emps.IsLeave,
                             MobileTel = emps.MobileTel,
                             Name = emps.Name,
                             OrginazationCode = companies.OrginazationCode,
                             Post_Corp = posts.Post_Corp,
                             Post_Major = posts.Post_Major,
                             Post_psDate = posts.Post_psDate,
                             Post_psOrg = posts.Post_psOrg,
                             Post_psZG = posts.Post_psZG,
                             Post_psZGCode = posts.Post_psZGCode,
                             PostId = posts.Id,
                             pwd = emps.pwd,
                             Sex = emps.Sex,
                             SpecialityID = emps.SpecialityID,
                             Tel = emps.Tel,
                             TypeFlag = emps.TypeFlag,
                             ZhiWu = emps.ZhiWu,
                             TypeFlags = titles.TypeFlags,
                             CertificateCode = titles.CertificateCode,
                             CertificateLevel = titles.CertificateLevel,
                             CertificateName = titles.CertificateName,
                             CertificateSpecialty = titles.CertificateSpecialty,
                             IfHaveCA = emps.IfHaveCA,
                             isZZEmp = emps.isZZEmp,
                             AppID = emps.AppID,
                             ICCard = emps.ICCard
                             #endregion
                         };

            if ("06" == preAreaCode)
            {
                query1 = query1.Where(c => c.AppID == appid);
            }

            var result = query1.OrderBy(q => q.EmpGuid).ToList();
            ////3.封装数据。
            ////取得职称名
            Dictionary<string, string> data = (from dic in zbdlcontext.a_PostPszgDefine
                                               select new { dic.Code, dic.Title }).ToDictionary(p => p.Code, p => p.Title);
            var managers = new List<tb_Emp_Manager>();
            ////如果实体需要翻译，在此循环遍历翻译。
            string strTitleDetails = string.Empty;
            string titleCode = string.Empty;
            foreach (var manager in result)
            {
                var mgr = managers.SingleOrDefault(m => m.EmpGuid == manager.EmpGuid);
                if (mgr != null)
                {
                    if (!string.IsNullOrEmpty(mgr.CertificateCode))
                    {
                        if (!titleCode.Split(',').Contains(manager.CertificateCode))
                        {
                            titleCode += "," + manager.CertificateCode;
                            strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                            mgr.StrTitleDetails += "<br/>" + strTitleDetails;
                        }
                    }
                }
                else
                {//审核状态
                    //m.FlowCode = GetManagerFlowCode(m, areaCode);
                    manager.StrFlowCode = GetFlowCodeTitle(
                            manager.FlowCode,
                            manager.ClassId.ToString(), areaCode);
                    //职称
                    if (manager.Post_psZG != null && data.ContainsKey(manager.Post_psZG))
                    {
                        manager.Post_Title += data[manager.Post_psZG];
                    }
                    if (manager.Post_psZGCode != null && data.ContainsKey(manager.Post_psZGCode))
                    {
                        manager.Post_Title += data[manager.Post_psZGCode];
                    }

                    //证书
                    if (!string.IsNullOrEmpty(manager.CertificateCode))
                    {
                        titleCode += "," + manager.CertificateCode;
                        strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                        manager.StrTitleDetails = strTitleDetails;
                    }
                    managers.Add(manager);
                }
            }
            return managers;
        }

        /// <summary>
        /// 返回其他人员列表数目
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetEmpManagerOtherListCount(string conditions, string certList, string areaCode)
        {
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on new
                        {
                            EmpGuid = emps.EmpGuid,
                            IsDel = (bool?)false
                        } equals new
                        {
                            EmpGuid = post.EmpGuid,
                            IsDel = post.IsDel
                        }
                    into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on new
                        {
                            EmpGuid = (Guid?)emps.EmpGuid,
                            IsDel = (bool?)false
                        }
                        equals new
                        {
                            EmpGuid = title.EmpGuid,
                            IsDel = title.IsDel
                        }
                        into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体

                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            Post_Corp = posts.Post_Corp,
                            Post_Major = posts.Post_Major,
                            Post_psDate = posts.Post_psDate,
                            Post_psOrg = posts.Post_psOrg,
                            Post_psZG = posts.Post_psZG,
                            Post_psZGCode = posts.Post_psZGCode,
                            PostId = posts.Id,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            StampCode = titles.StampCode,
                            AppID = emps.AppID
                            #endregion
                        };
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            //其他人员验证
            var guidEmp = new List<Guid>();
            if (!string.IsNullOrEmpty(certList))
            {
                var list = JsonConvert.DeserializeObject<List<int>>(certList);
                guidEmp = query.Where(q => list.Contains(q.TypeFlags ?? -1)).Select(q => q.EmpGuid).ToList().Distinct().ToList();
                query = query.Where(q => !list.Contains(q.TypeFlags ?? -1));
            }//end
            var empGuids = new List<Guid>();
            empGuids = query.Select(q => q.EmpGuid).ToList();
            //过滤多证重复人员
            if (guidEmp != null && guidEmp.Count > 0)
            {
                empGuids = empGuids.Where(e => !guidEmp.Contains(e)).ToList();
            } //end     
            return empGuids.Distinct().Count();
        }

        /// <summary>
        /// 按证书类别分组取得人员列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetEmpManagerByCertList(int pageCount, int pageSize, string conditions, string certList, string areaCode)
        {
            ////1.查询满足条件的用户guid。
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            //var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on new
                        {
                            EmpGuid = emps.EmpGuid,
                            IsDel = (bool?)false
                        } equals new
                        {
                            EmpGuid = post.EmpGuid,
                            IsDel = post.IsDel
                        }
                        into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on new
                        {
                            EmpGuid = (Guid?)emps.EmpGuid,
                            IsDel = (bool?)false
                        }
                        equals new
                        {
                            EmpGuid = title.EmpGuid,
                            IsDel = title.IsDel
                        }
                        into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            Post_Corp = posts.Post_Corp,
                            Post_Major = posts.Post_Major,
                            Post_psDate = posts.Post_psDate,
                            Post_psOrg = posts.Post_psOrg,
                            Post_psZG = posts.Post_psZG,
                            Post_psZGCode = posts.Post_psZGCode,
                            PostId = posts.Id,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            CLCode=titles.CLCode,
                            CSCode=titles.CSCode,
                            StampCode = titles.StampCode,
                            GroupID = emps.GroupID,
                            GroupTreeID = titles.GroupTreeID,
                            IfHaveCA = emps.IfHaveCA,
                            isZZEmp = emps.isZZEmp,
                            AppID = emps.AppID,
                            ICCard = emps.ICCard
                            #endregion
                        };
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoConditionNew>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            //其他人员验证
            var guidEmp = new List<Guid>();
            if (!string.IsNullOrEmpty(certList))
            {
                var list = JsonConvert.DeserializeObject<List<int>>(certList);
                guidEmp = query.Where(q => list.Contains(q.TypeFlags ?? -1)).Select(q => q.EmpGuid).ToList().Distinct().ToList();
                query = query.Where(q => !list.Contains(q.TypeFlags ?? -1));
            }//end
            var empGuids = new List<Guid>();
            empGuids = query.Select(q => q.EmpGuid).ToList();
            //过滤多证重复人员
            if (guidEmp != null && guidEmp.Count > 0)
            {
                empGuids = empGuids.Where(e => !guidEmp.Contains(e)).ToList();
            }//end

            if (pageSize > 0)
            {
                empGuids = empGuids.Distinct().OrderBy(e => e).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                empGuids = empGuids.Distinct().ToList();
            }
            ////2.查询人员信息。
            var query1 = from emps in dbEmp
                         join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                         join post in dbEmpPost on new
                         {
                             EmpGuid = emps.EmpGuid,
                             IsDel = (bool?)false
                         } equals new
                         {
                             EmpGuid = post.EmpGuid,
                             IsDel = post.IsDel
                         } into jPosts
                         from posts in jPosts.DefaultIfEmpty()
                         join title in dbTitles on new
                         {
                             EmpGuid = (Guid?)emps.EmpGuid,
                             IsDel = (bool?)false
                         }
                         equals new
                         {
                             EmpGuid = title.EmpGuid,
                             IsDel = title.IsDel
                         } into jTitles
                         from titles in jTitles.DefaultIfEmpty()
                         where emps.FlowAreaCode == areaCode && empGuids.Contains(emps.EmpGuid) && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                         select new tb_Emp_Manager()
                         {
                             #region 封装实体

                             EmpGuid = emps.EmpGuid,
                             AreaCode = emps.AreaCode,
                             FlowCode = emps.RealFlowCode,
                             corpName = companies.CorpName,
                             Birthday = emps.Birthday,
                             BithdayMonth = emps.BithdayMonth,
                             BithdayYear = emps.BithdayYear,
                             ClassId = emps.ClassId,
                             CorpClassID = emps.CorpClassID,
                             CorpGuid = emps.CorpGuid,
                             CorpID = emps.CorpID,
                             CreatDate = emps.CreatDate,
                             DogID = emps.DogID,
                             DoMajor = emps.DoMajor,
                             Duty = emps.Duty,
                             DutyLevel = emps.Duty,
                             Education = emps.Education,
                             EMail = emps.EMail,
                             empdogid = emps.empdogid,
                             EmployeeType = emps.EmployeeType,
                             GraduatedSchool = emps.GraduatedSchool,
                             ID = emps.ID,
                             IDCard = emps.IDCard,
                             IDType = emps.IDType,
                             InsuranceNum = emps.InsuranceNum,
                             //InsutanceCode=emps.
                             isFreeze = emps.isFreeze,
                             IsLeave = emps.IsLeave,
                             MobileTel = emps.MobileTel,
                             Name = emps.Name,
                             OrginazationCode = companies.OrginazationCode,
                             Post_Corp = posts.Post_Corp,
                             Post_Major = posts.Post_Major,
                             Post_psDate = posts.Post_psDate,
                             Post_psOrg = posts.Post_psOrg,
                             Post_psZG = posts.Post_psZG,
                             Post_psZGCode = posts.Post_psZGCode,
                             PostId = posts.Id,
                             pwd = emps.pwd,
                             Sex = emps.Sex,
                             SpecialityID = emps.SpecialityID,
                             Tel = emps.Tel,
                             TypeFlag = emps.TypeFlag,
                             ZhiWu = emps.ZhiWu,
                             TypeFlags = titles.TypeFlags,
                             CertificateCode = titles.CertificateCode,
                             CertificateLevel = titles.CertificateLevel,
                             CertificateName = titles.CertificateName,
                             CertificateSpecialty = titles.CertificateSpecialty,
                             CSCode=titles.CSCode,
                             CLCode=titles.CLCode,
                             GroupID = emps.GroupID,
                             GroupTreeID = titles.GroupTreeID,
                             IfHaveCA = emps.IfHaveCA,
                             isZZEmp = emps.isZZEmp,
                             AppID = emps.AppID,
                             ICCard = emps.ICCard
                             #endregion
                         };

            if ("06" == preAreaCode)
            {
                query1 = query1.Where(c => c.AppID == appid);
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoConditionNew>>(conditions);
                query1 = query1.BuildCondition<tb_Emp_Manager>(condition);
            }

            var result = query1.OrderBy(q => q.EmpGuid).ToList();
            ////3.封装数据。
            ////取得职称名
            Dictionary<string, string> data = (from dic in zbdlcontext.a_PostPszgDefine
                                               select new { dic.Code, dic.Title }).ToDictionary(p => p.Code, p => p.Title);
            var managers = new List<tb_Emp_Manager>();
            ////如果实体需要翻译，在此循环遍历翻译。
            string strTitleDetails = string.Empty;
            string titleCode = string.Empty;
            foreach (var manager in result)
            {
                var mgr = managers.SingleOrDefault(m => m.EmpGuid == manager.EmpGuid);
                if (mgr != null)
                {
                    if (!string.IsNullOrEmpty(mgr.CertificateCode))
                    {
                        if (!titleCode.Split(',').Contains(manager.CertificateCode))
                        {
                            titleCode += "," + manager.CertificateCode;
                            strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                            mgr.StrTitleDetails += "<br/>" + strTitleDetails;
                        }
                    }
                }
                else
                {//审核状态
                    //m.FlowCode = GetManagerFlowCode(m, areaCode);
                    manager.StrFlowCode = GetFlowCodeTitle(
                            manager.FlowCode,
                            manager.ClassId.ToString(), areaCode);
                    //职称
                    if (manager.Post_psZG != null && data.ContainsKey(manager.Post_psZG))
                    {
                        manager.Post_Title += data[manager.Post_psZG];
                    }
                    if (manager.Post_psZGCode != null && data.ContainsKey(manager.Post_psZGCode))
                    {
                        manager.Post_Title += data[manager.Post_psZGCode];
                    }

                    //证书
                    if (!string.IsNullOrEmpty(manager.CertificateCode))
                    {
                        titleCode += "," + manager.CertificateCode;
                        strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                        manager.StrTitleDetails = strTitleDetails;
                    }
                    managers.Add(manager);
                }
            }
            return managers;
        }

        /// <summary>
        /// 按证书类别分组取得人员数目
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetEmpManagerByCertCount(string conditions, string certList, string areaCode)
        {
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on new
                        {
                            EmpGuid = emps.EmpGuid,
                            IsDel = (bool?)false
                        } equals new
                        {
                            EmpGuid = post.EmpGuid,
                            IsDel = post.IsDel
                        }
                    into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on new
                        {
                            EmpGuid = (Guid?)emps.EmpGuid,
                            IsDel = (bool?)false
                        }
                        equals new
                        {
                            EmpGuid = title.EmpGuid,
                            IsDel = title.IsDel
                        }
                        into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体

                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            Post_Corp = posts.Post_Corp,
                            Post_Major = posts.Post_Major,
                            Post_psDate = posts.Post_psDate,
                            Post_psOrg = posts.Post_psOrg,
                            Post_psZG = posts.Post_psZG,
                            Post_psZGCode = posts.Post_psZGCode,
                            PostId = posts.Id,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            GroupID = emps.GroupID,
                            GroupTreeID = titles.GroupTreeID,
                            StampCode = titles.StampCode,
                            AppID = emps.AppID
                            #endregion
                        };
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoConditionNew>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            //其他人员验证
            var guidEmp = new List<Guid>();
            if (!string.IsNullOrEmpty(certList))
            {
                var list = JsonConvert.DeserializeObject<List<int>>(certList);
                guidEmp = query.Where(q => list.Contains(q.TypeFlags ?? -1)).Select(q => q.EmpGuid).ToList().Distinct().ToList();
                query = query.Where(q => !list.Contains(q.TypeFlags ?? -1));
            }//end
            var empGuids = new List<Guid>();
            empGuids = query.Select(q => q.EmpGuid).ToList();
            //过滤多证重复人员
            if (guidEmp != null && guidEmp.Count > 0)
            {
                empGuids = empGuids.Where(e => !guidEmp.Contains(e)).ToList();
            } //end     
            return empGuids.Distinct().Count();
        }

        /// <summary>
        /// 按证书类别获取人员
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="certList"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetEmpManagerByCerts(out int cnt, int pageCount, int pageSize, string conditions, string certList, string areaCode)
        {
            ////1.查询满足条件的用户guid。
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            //var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on new
                        {
                            EmpGuid = emps.EmpGuid,
                            IsDel = (bool?)false
                        } equals new
                        {
                            EmpGuid = post.EmpGuid,
                            IsDel = post.IsDel
                        }
                        into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on new
                        {
                            EmpGuid = (Guid?)emps.EmpGuid,
                            IsDel = (bool?)false
                        }
                        equals new
                        {
                            EmpGuid = title.EmpGuid,
                            IsDel = title.IsDel
                        }
                        into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null) && emps.TypeFlag != null && (emps.TypeFlag.Contains("-1") || emps.TypeFlag.Contains("3") || emps.TypeFlag.Contains("4") || emps.TypeFlag.Contains("5"))
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = titles.FlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            Post_Corp = posts.Post_Corp,
                            Post_Major = posts.Post_Major,
                            Post_psDate = posts.Post_psDate,
                            Post_psOrg = posts.Post_psOrg,
                            Post_psZG = posts.Post_psZG,
                            Post_psZGCode = posts.Post_psZGCode,
                            PostId = posts.Id,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags ?? -1,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            StampCode = titles.StampCode,
                            IfHaveCA = emps.IfHaveCA,
                            isZZEmp = emps.isZZEmp,
                            AppID = emps.AppID
                            #endregion
                        };
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            ////取出拥有证书的人员
            var guidEmp = new List<Guid>();
            if (!string.IsNullOrEmpty(certList))
            {
                var list = JsonConvert.DeserializeObject<List<int>>(certList);
                guidEmp = query.Where(q => !list.Contains(q.TypeFlags ?? -1)).Select(q => q.EmpGuid).ToList().Distinct().ToList();
                query = query.Where(q => list.Contains(q.TypeFlags ?? -1));
            }//end
            var empGuids = new List<Guid>();
            empGuids = query.Select(q => q.EmpGuid).ToList();
            //过滤多证重复人员
            if (guidEmp != null && guidEmp.Count > 0)
            {
                empGuids = empGuids.Where(e => !guidEmp.Contains(e)).ToList();
            }//end
            ////获取总数
            cnt = empGuids.Distinct().Count();
            if (pageSize > 0)
            {
                empGuids = empGuids.Distinct().OrderBy(e => e).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                empGuids = empGuids.Distinct().ToList();
            }
            ////2.查询人员信息。
            var query1 = from emps in dbEmp
                         join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                         join post in dbEmpPost on new
                         {
                             EmpGuid = emps.EmpGuid,
                             IsDel = (bool?)false
                         } equals new
                         {
                             EmpGuid = post.EmpGuid,
                             IsDel = post.IsDel
                         } into jPosts
                         from posts in jPosts.DefaultIfEmpty()
                         join title in dbTitles on new
                         {
                             EmpGuid = (Guid?)emps.EmpGuid,
                             IsDel = (bool?)false
                         }
                         equals new
                         {
                             EmpGuid = title.EmpGuid,
                             IsDel = title.IsDel
                         } into jTitles
                         from titles in jTitles.DefaultIfEmpty()
                         where emps.FlowAreaCode == areaCode && empGuids.Contains(emps.EmpGuid) && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null) && (titles.TypeFlags == null || titles.TypeFlags == 1015)
                         select new tb_Emp_Manager()
                         {
                             #region 封装实体

                             EmpGuid = emps.EmpGuid,
                             AreaCode = emps.AreaCode,
                             FlowCode = titles.FlowCode,
                             corpName = companies.CorpName,
                             Birthday = emps.Birthday,
                             BithdayMonth = emps.BithdayMonth,
                             BithdayYear = emps.BithdayYear,
                             ClassId = emps.ClassId,
                             CorpClassID = emps.CorpClassID,
                             CorpGuid = emps.CorpGuid,
                             CorpID = emps.CorpID,
                             CreatDate = emps.CreatDate,
                             DogID = emps.DogID,
                             DoMajor = emps.DoMajor,
                             Duty = emps.Duty,
                             DutyLevel = emps.Duty,
                             Education = emps.Education,
                             EMail = emps.EMail,
                             empdogid = emps.empdogid,
                             EmployeeType = emps.EmployeeType,
                             GraduatedSchool = emps.GraduatedSchool,
                             ID = emps.ID,
                             IDCard = emps.IDCard,
                             IDType = emps.IDType,
                             InsuranceNum = emps.InsuranceNum,
                             //InsutanceCode=emps.
                             isFreeze = emps.isFreeze,
                             IsLeave = emps.IsLeave,
                             MobileTel = emps.MobileTel,
                             Name = emps.Name,
                             OrginazationCode = companies.OrginazationCode,
                             Post_Corp = posts.Post_Corp,
                             Post_Major = posts.Post_Major,
                             Post_psDate = posts.Post_psDate,
                             Post_psOrg = posts.Post_psOrg,
                             Post_psZG = posts.Post_psZG,
                             Post_psZGCode = posts.Post_psZGCode,
                             PostId = posts.Id,
                             pwd = emps.pwd,
                             Sex = emps.Sex,
                             SpecialityID = emps.SpecialityID,
                             Tel = emps.Tel,
                             TypeFlag = emps.TypeFlag,
                             ZhiWu = emps.ZhiWu,
                             TypeFlags = titles.TypeFlags,
                             CertificateCode = titles.CertificateCode,
                             CertificateLevel = titles.CertificateLevel,
                             CertificateName = titles.CertificateName,
                             CertificateSpecialty = titles.CertificateSpecialty,
                             IfHaveCA = emps.IfHaveCA,
                             isZZEmp = emps.isZZEmp,
                             AppID = emps.AppID
                             #endregion
                         };

            if ("06" == preAreaCode)
            {
                query1 = query1.Where(c => c.AppID == appid);
            }

            var result = query1.OrderBy(q => q.EmpGuid).ToList();
            ////3.封装数据。
            ////取得职称名
            Dictionary<string, string> data = (from dic in zbdlcontext.a_PostPszgDefine
                                               select new { dic.Code, dic.Title }).ToDictionary(p => p.Code, p => p.Title);
            var managers = new List<tb_Emp_Manager>();
            ////如果实体需要翻译，在此循环遍历翻译。
            string strTitleDetails = string.Empty;
            string titleCode = string.Empty;
            foreach (var manager in result)
            {
                var mgr = managers.SingleOrDefault(m => m.EmpGuid == manager.EmpGuid);
                if (mgr != null)
                {
                    if (!string.IsNullOrEmpty(mgr.CertificateCode))
                    {
                        if (!titleCode.Split(',').Contains(manager.CertificateCode))
                        {
                            titleCode += "," + manager.CertificateCode;
                            strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                            mgr.StrTitleDetails += "<br/>" + strTitleDetails;
                        }
                    }
                }
                else
                {//审核状态
                    //m.FlowCode = GetManagerFlowCode(m, areaCode);
                    manager.StrFlowCode = GetFlowCodeTitle(
                            manager.FlowCode,
                            "2601", areaCode);
                    //职称
                    if (manager.Post_psZG != null && data.ContainsKey(manager.Post_psZG))
                    {
                        manager.Post_Title += data[manager.Post_psZG];
                    }
                    if (manager.Post_psZGCode != null && data.ContainsKey(manager.Post_psZGCode))
                    {
                        manager.Post_Title += data[manager.Post_psZGCode];
                    }
                    //证书
                    if (!string.IsNullOrEmpty(manager.CertificateCode))
                    {
                        titleCode += "," + manager.CertificateCode;
                        strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                        manager.StrTitleDetails = strTitleDetails;
                    }
                    managers.Add(manager);
                }
            }
            return managers;
        }

        public override IList<DTO.tb_Emp_Manager> GetEmpManagerCertList(out int cnt, int pageCount, int pageSize, string conditions, string areaCode)
        {
            ////1.查询满足条件的用户guid。
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            //var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var query = from titles in dbTitles
                        join emps in dbEmp on new
                        {
                            EmpGuid = titles.EmpGuid,
                            IsDel = titles.IsDel
                        }
                        equals new
                        {
                            EmpGuid = (Guid?)emps.EmpGuid,
                            IsDel = (bool?)false
                        }
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        && (titles.IsDel == false || titles.IsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = titles.FlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags ?? -1,
                            EducationGuid = titles.EducationGUID,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            GroupTreeID = titles.GroupTreeID,
                            StampCode = titles.StampCode,
                            IfHaveCA = emps.IfHaveCA,
                            isZZEmp = emps.isZZEmp,
                            AppID = emps.AppID,
                            GroupID = emps.GroupID
                            #endregion
                        };
            int appid = 0;
            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
            string preAreaCode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if ("06" == preAreaCode)
            {
                query = query.Where(c => c.AppID == appid);
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoConditionNew>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }

            var eduGuids = new List<Guid?>();
            eduGuids = query.Select(q => q.EducationGuid).ToList();
            ////获取总数
            cnt = eduGuids.Distinct().Count();
            if (pageSize > 0)
            {
                eduGuids = eduGuids.Distinct().OrderBy(e => e).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                eduGuids = eduGuids.Distinct().ToList();
            }
            ////2.查询人员信息。
            var query1 = from titles in dbTitles
                         join emps in dbEmp on new
                         {
                             EmpGuid = titles.EmpGuid,
                             IsDel = titles.IsDel
                         }
                         equals new
                         {
                             EmpGuid = (Guid?)emps.EmpGuid,
                             IsDel = (bool?)false
                         }
                         join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                         where emps.FlowAreaCode == areaCode && eduGuids.Contains(titles.EducationGUID) && (emps.IsDel == null || emps.IsDel == false)
                         && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                         && (titles.IsDel == false || titles.IsDel == null)
                         select new tb_Emp_Manager()
                         {
                             #region 封装实体

                             EmpGuid = emps.EmpGuid,
                             AreaCode = emps.AreaCode,
                             FlowCode = titles.FlowCode,
                             corpName = companies.CorpName,
                             Birthday = emps.Birthday,
                             BithdayMonth = emps.BithdayMonth,
                             BithdayYear = emps.BithdayYear,
                             ClassId = emps.ClassId,
                             CorpClassID = emps.CorpClassID,
                             CorpGuid = emps.CorpGuid,
                             CorpID = emps.CorpID,
                             CreatDate = emps.CreatDate,
                             DogID = emps.DogID,
                             DoMajor = emps.DoMajor,
                             Duty = emps.Duty,
                             DutyLevel = emps.Duty,
                             Education = emps.Education,
                             EMail = emps.EMail,
                             empdogid = emps.empdogid,
                             EmployeeType = emps.EmployeeType,
                             GraduatedSchool = emps.GraduatedSchool,
                             ID = emps.ID,
                             IDCard = emps.IDCard,
                             IDType = emps.IDType,
                             InsuranceNum = emps.InsuranceNum,
                             //InsutanceCode=emps.
                             isFreeze = emps.isFreeze,
                             IsLeave = emps.IsLeave,
                             MobileTel = emps.MobileTel,
                             Name = emps.Name,
                             OrginazationCode = companies.OrginazationCode,
                             pwd = emps.pwd,
                             Sex = emps.Sex,
                             SpecialityID = emps.SpecialityID,
                             Tel = emps.Tel,
                             TypeFlag = emps.TypeFlag,
                             ZhiWu = emps.ZhiWu,
                             EducationGuid = titles.EducationGUID,
                             TypeFlags = titles.TypeFlags,
                             CertificateCode = titles.CertificateCode,
                             CertificateLevel = titles.CertificateLevel,
                             CertificateName = titles.CertificateName,
                             CertificateSpecialty = titles.CertificateSpecialty,
                             CertClassId = titles.ClassID,
                             GroupTreeID = titles.GroupTreeID,
                             IfHaveCA = emps.IfHaveCA,
                             isZZEmp = emps.isZZEmp,
                             AppID = emps.AppID,
                             GroupID = emps.GroupID
                             #endregion
                         };

            if ("06" == preAreaCode)
            {
                query1 = query1.Where(c => c.AppID == appid);
            }
            var result = query1.OrderBy(q => q.EmpGuid).ToList();
            var managers = new List<tb_Emp_Manager>();
            ////如果实体需要翻译，在此循环遍历翻译。
            string strTitleDetails = string.Empty;
            string titleCode = string.Empty;
            foreach (var manager in result)
            {
                titleCode = manager.CertificateCode;
                strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                ////审核状态
                manager.StrFlowCode = GetFlowCodeTitle(manager.FlowCode, manager.CertClassId == null ? "2611" : manager.CertClassId.ToString(), areaCode);
                manager.StrTitleDetails = strTitleDetails;
                managers.Add(manager);
            }
            return managers;
        }
        #endregion

        #region 人员上报、审核

        /// <summary>
        /// 人员上报、审核、退回
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="optType"></param>
        /// <param name="areaCode"></param>
        /// <param name="massage"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpInfoReportOrAudit(string corpUserGuid,
            IList<string> emps,
            int optType,
            string areaCode,
            string massage,
            string description)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string empName = "";
            ////用户验证
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result || result0.ReturnValue == null)
            {
                result.Result = false;
                result.Message = "登录用户信息有误！";
                return result;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            try
            {
                foreach (var item in emps)
                {
                    ////判断人员是否存在
                    DTO.OperationResult result1 = CheckEmpIsExist(item.Trim());
                    if (!result1.Result)
                    {
                        result.Message += result1.Message;
                        continue;
                    }
                    tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result1.ReturnValue;
                    ////取得审核状态
                    DTO.OperationResult result2 = CheckFlowCode(item.Trim(), optType, currentManager.ClassId, userInfo.RoleID.ToString(), areaCode, areaCode);
                    if (!result2.Result)
                    {
                        // result.Message += "您不能对人员" + currentManager.Name + "的执行此操作！";
                        continue;
                    }
                    string code = result2.ReturnValue.ToString();
                    if (string.IsNullOrEmpty(code))
                    {
                        continue;
                    }
                    ////修改审核状态
                    DTO.OperationResult result3 = EmpFlowCodeEdit(currentManager.EmpGuid.ToString(), currentManager.ClassId, areaCode, code, description);
                    EmpFlowCodeEdit(currentManager.EmpGuid, code);
                    // result.Message += currentManager.Name + result3.Message;
                    empName += currentManager.Name + ",";
                    result.Result = result3.Result;
                    ////日志
                    if (description.Length > 0)
                    {
                        massage += "<br/>审核意见：" + description;
                    }
                    var flag = SetUserLog(massage, currentManager, "", optType.ToString(), areaCode, corpUserGuid);
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message += currentManager.Name + "日志写入出错！";
                    }
                }
                if (empName.Length > 1)
                {
                    result.Message += "人员[" + empName.TrimEnd(',') + "]操作执行成功！";
                }
                else
                {
                    result.Message += "操作执行失败，请确认选择人员的审核状态！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                if (empName.Length > 1)
                {
                    empName = empName.TrimEnd(',');
                    if (result.Message.IndexOf(empName) < 0)
                    {
                        result.Message += "人员[" + empName + "]操作执行成功！";
                    }
                }
                result.Message = massage + "失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }

        /// <summary>
        /// 上报，取消上报，审核，退回人员信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoPost(string corpUserGuid, IList<string> emps, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (log == null)
            {
                result.Result = false;
                result.Message = "参数错误！";
                return result;
            }
            //参数不够使用log传递参数
            int optType = 4;
            int.TryParse(log.FunctionId, out optType);
            string message = log.FunctionType;
            string description = log.Notice;
            return EmpInfoReportOrAudit(corpUserGuid, emps, optType, areaCode, message, description);
        }

        /// <summary>
        /// 上报，取消上报，审核，退回证书信息
        /// </summary>
        /// <param name="empGuids"></param>
        /// <param name="isAuditQualities"></param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <param name="description"></param>
        /// <param name="isFinal"></param>
        /// <param name="isunlockandback"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoAudit(List<string> empGuids, bool isAuditQualities, string areaCode, string log, string flowCode, string description, bool isFinal, bool isunlockandback)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            User_Log logInfo = JsonConvert.DeserializeObject<User_Log>(log);
            if (logInfo == null)
            {
                result.Result = false;
                result.Message = "参数错误！";
                return result;
            }
            int optType = 5;
            string corpUserGuid = logInfo.IsrtUser.Trim();
            string message = logInfo.FunctionType;
            string codeType = logInfo.IsrtUserRole;
            string empGuid = logInfo.IsrtUserName;
            string roleId = logInfo.IsrtUserArea;
            int.TryParse(logInfo.FunctionId, out optType);

            //证书上报审核
            return EmpInfoReportOrAudit(corpUserGuid, empGuids, optType, areaCode, message, description, codeType, empGuid, roleId);

        }
        /// <summary>
        /// 人员职业手册上报审核
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="optType"></param>
        /// <param name="areaCode"></param>
        /// <param name="massage"></param>
        /// <param name="description"></param>
        /// <param name="codeType"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpInfoReportOrAudit(string corpUserGuid,
        IList<string> emps,
        int optType,
        string areaCode,
        string massage,
        string description, string codeType, string empGuid, string roleId)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            int classId = int.Parse(codeType);
            string CertificateName = string.Empty;
            try
            {
                ////判断人员是否存在
                DTO.OperationResult result1 = CheckEmpIsExist(empGuid.Trim());
                if (!result1.Result)
                {
                    result.Message += result1.Message;
                    return result;
                }
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result1.ReturnValue;
                foreach (var item in emps)
                {
                    //判断证书是否存在
                    DTO.OperationResult result0 = CheckQualityIsExist(item.Trim());
                    if (!result0.Result)
                    {
                        continue;
                    }
                    Tb_Emp_TitleDetails_Zbdl empquality = (Tb_Emp_TitleDetails_Zbdl)result0.ReturnValue;
                    ////取得审核状态
                    DTO.OperationResult result2 = CheckFlowCode(item.Trim(), optType, classId, roleId, string.Empty, string.Empty);
                    if (!result2.Result)
                    {
                        result.Message += "您不能对证书[" + empquality.CertificateName + "]执行此操作！";
                        continue;
                    }
                    string code = result2.ReturnValue.ToString();
                    if (string.IsNullOrEmpty(code))
                    {
                        continue;
                    }
                    ////修改审核状态
                    DTO.OperationResult result3 = EmpFlowCodeEdit(item.ToString(), classId, areaCode, code, description);
                    CertificateName += empquality.CertificateName + ",";
                    result.Result = result3.Result;
                    ////日志
                    if (description.Length > 0)
                    {
                        massage += "<br/>审核意见：" + description;
                    }
                    var flag = SetUserLog(massage, currentManager, classId.ToString(), optType.ToString(), areaCode, corpUserGuid);
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message += currentManager.Name + "日志写入出错！";
                    }
                }
                if (CertificateName.Length > 1)
                {
                    result.Message += "证书[" + CertificateName.TrimEnd(',') + "]操作执行成功！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                if (CertificateName.Length > 1)
                {
                    CertificateName = CertificateName.TrimEnd(',');
                    if (result.Message.IndexOf(CertificateName) < 0)
                    {
                        result.Message += "证书[" + CertificateName.TrimEnd(',') + "]操作执行成功！";
                    }
                }
                result.Message = massage + "失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }
        /// <summary>
        /// 返回审核状态
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="empGuid"></param>
        /// <param name="optType"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetFlowCodes(string corpUserGuid, string empGuid, int optType, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            bool status = true;//企业状态标识
            try
            {
                ////用户信息
                DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
                if (!result0.Result || result0.ReturnValue == null)
                {
                    result.Result = false;
                    result.Message = "登录用户信息有误！";
                    return result;
                }
                var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
                ////判断人员是否存在
                result = CheckEmpIsExist(empGuid);
                if (!result.Result)
                {
                    return result;
                }
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                ///如果人员即是管理人员又是从业人员
                status = CheckManagerStatus(currentManager, 4, areaCode);
                ////取得审核状态
                List<DTO.OperationResult> resultList = new List<DTO.OperationResult>();
                string area = string.Empty;
                for (int i = 0; i <= optType; i++)
                {
                    if (i > 3)
                    {
                        area = areaCode; ////本地审核状态
                    }
                    DTO.OperationResult result1 = CheckFlowCode(empGuid, i, currentManager.ClassId, userInfo.RoleID.ToString(), area, areaCode);
                    if (i < 4 && !status)//管理人员信息不可修改
                    {
                        //result1.Result = false;
                    }
                    resultList.Add(result1);
                }
                result.Result = true;
                result.ReturnValue = resultList;
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "获取审核状态失败" + ex.Message;
                result.Result = false;
            }
            return result;
        }
        /// <summary>
        /// 返回人员在各市场的审核状态
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override List<FlowStatus> GetEmpFlowStatus(string empGuid, string areaCode)
        {
            try
            {
                ////取得人员
                DTO.OperationResult result = new DTO.OperationResult();
                result = CheckEmpIsExist(empGuid);
                if (!result.Result)
                {
                    return null;
                }
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                ////用户信息
                DTO.OperationResult result0 = CheckUserIsExist(currentManager.CorpGuid.ToString());
                if (!result0.Result || result0.ReturnValue == null)
                {
                    return null;
                }
                var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
                ////取得当前审核状态
                var flowCodes = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid.Trim() && f.CodeType == currentManager.ClassId && f.IsDel == false).ToList();
                ////返回flowcode状态
                OptType opt = (OptType)System.Enum.Parse(typeof(OptType), "4");////当前操作
                BasicBLL bll = new BasicBLL();
                List<FlowStatus> flowList = new List<FlowStatus>();
                foreach (Tb_FlowCode_Zbdl flowCode in flowCodes)
                {
                    FlowStatus flow = new FlowStatus();
                    flow.AreaCode = flowCode.AreaCode;
                    flow.AreaCodeTitle = bll.GetAreaCodeTitle(flowCode.AreaCode);
                    flow.FlowCode = flowCode.FlowCode;
                    flow.FlowCodeTitle = GetFlowCodeTitle(flowCode.FlowCode, currentManager.ClassId.ToString(), flowCode.AreaCode);
                    //人员审核状态
                    var result1 = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                      userInfo.RoleID.ToString(), string.Empty,
                                      flowCode.AreaCode,
                                      flowCode.CodeType.ToString(), flowCode.FlowCode, opt);
                    flow.CanEdit = result1.Result;
                    //管理人员判断
                    if (!CheckManagerStatus(currentManager, 4, flowCode.AreaCode) && flow.CanEdit)
                    {
                        flow.CanEdit = false;
                        flow.FlowCodeTitle = "管理人员";
                    }

                    flowList.Add(flow);
                }
                return flowList;
            }
            catch { return null; }
        }
        #endregion

        #region 导入当前市场
        /// <summary>
        /// 将人员导入当前市场
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoImport(string corpUserGuid, IList<string> emps, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string empName = "";
            ////用户验证
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result || result0.ReturnValue == null)
            {
                result.Result = false;
                result.Message = "登录用户信息有误！";
                return result;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            try
            {
                foreach (var item in emps)
                {
                    ////判断人员是否存在
                    DTO.OperationResult result1 = CheckEmpIsExist(item.Trim());
                    if (!result1.Result)
                    {
                        result.Message += result1.Message;
                        continue;
                    }
                    tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result1.ReturnValue;
                    EmpFlowCode(currentManager.EmpGuid.ToString(), currentManager.ClassId, areaCode);
                    empName += currentManager.Name + ",";
                }
                if (empName.Length > 1)
                {
                    result.Message += "人员[" + empName.TrimEnd(',') + "]导入执行成功！";
                }
                result.Result = true;
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                if (empName.Length > 1)
                {
                    empName = empName.TrimEnd(',');
                    if (result.Message.IndexOf(empName) < 0)
                    {
                        result.Message += "人员[" + empName + "]导入执行成功！";
                    }
                }
                result.Message = "人员导入过程出错：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }

        /// <summary>
        /// 取得企业待导入当前市场的人员
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetEmpImportList(int pageCount, int pageSize, string conditions, string areaCode)
        {
            //取得所有人员
            var query = zbdlcontext.Emp_Manager.Where(p => (p.IsDel == false || p.IsDel == null));
            //取得当前地区的人员
            var dbEmp = zbdlcontext.ManagerInfoFlow.Where(e => (e.IsDel == false || e.IsDel == null) && e.FlowAreaCode == areaCode).Select(e => e);
            //过滤条件
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager_Zbdl>(condition);
                dbEmp = dbEmp.BuildCondition<V_EF_Manager>(condition);
            }
            //取得不在当前地区的人
            if (dbEmp.Count() > 0)
            {
                List<Guid> list = dbEmp.Select(d => d.EmpGuid).ToList();
                query = query.Where(q => !list.Contains(q.EmpGuid));
            }
            List<tb_Emp_Manager_Zbdl> emps = null;
            if (pageSize > 0)
            {
                emps = query.OrderByDescending(q => q.ID).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                emps = query.OrderByDescending(q => q.ID).ToList();
            }
            var emplist = new List<DTO.tb_Emp_Manager>();
            string empGuid = string.Empty;
            foreach (var emp in emps)
            {
                DTO.tb_Emp_Manager emp_D = new DTO.tb_Emp_Manager();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(emp, emp_D);
                emplist.Add(emp_D);
            }
            return emplist;
        }

        /// <summary>
        /// 取得企业待导入当前市场的人员数
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetEmpImportCount(string conditions, string areaCode)
        {
            //取得所有人员
            var query = zbdlcontext.Emp_Manager.Where(p => (p.IsDel == false || p.IsDel == null));
            //取得当前地区的人员
            var dbEmp = zbdlcontext.ManagerInfoFlow.Where(e => (e.IsDel == false || e.IsDel == null) && e.FlowAreaCode == areaCode).Select(e => e);
            //过滤条件
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager_Zbdl>(condition);
                dbEmp = dbEmp.BuildCondition<V_EF_Manager>(condition);
            }
            //取得不在当前地区的人
            if (dbEmp.Count() > 0)
            {
                List<Guid> list = dbEmp.Select(d => d.EmpGuid).ToList();
                query = query.Where(q => !list.Contains(q.EmpGuid));
            }
            return query.Count();
        }

        #endregion

        #region  人员统计

        /// <summary>
        /// 企业工作人员统计
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override List<KeyValue> GetEmpCounts(string corpUserGuid, string areaCode)
        {
            Guid corpGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out corpGuid))
            {
                return null;
            }
            var query = from emp in zbdlcontext.Emp_Manager
                        join empdtls in zbdlcontext.Emp_Qualities on emp.EmpGuid equals empdtls.EmpGuid
                        where emp.CorpGuid == corpGuid && (emp.IsDel == false || emp.IsDel == null) && (empdtls.IsDel == false || empdtls.IsDel == null)
                        group empdtls by empdtls.GroupTreeID into g
                        select new KeyValue
                        {
                            Key = System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)g.Max(p => p.GroupTreeID)).Trim(),
                            Value = System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)g.Count()).Trim(),
                        };
            var query1 = from obj in query
                         join dict in zbdlcontext.Dictionary on obj.Key equals dict.Code
                         where dict.RootCode == "ZGZSLC"
                         select new KeyValue
                         {
                             Key = dict.Name,
                             Value = obj.Value
                         };

            return query1.ToList();
        }

        /// <summary>
        /// 根据条件统计人员数目
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetEmpCount(string conditions, string areaCode)
        {
            var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
            var query = from emp in zbdlcontext.Emp_Manager
                        join empQualit in zbdlcontext.Emp_Qualities on emp.EmpGuid equals empQualit.EmpGuid into Qualits
                        from empQualits in Qualits.DefaultIfEmpty()
                        join empPost in zbdlcontext.Emp_Post on emp.EmpGuid equals empPost.EmpGuid into post
                        from empPosts in post.DefaultIfEmpty()
                        where (emp.IsDel == false || emp.IsDel == null) && (empQualits.IsDel == false || empQualits.IsDel == null)
                        select new EmpQueryCondition
                        {
                            ClassId = emp.ClassId,
                            Name = emp.Name,
                            EmpGuid = emp.EmpGuid,
                            CorpGuid = emp.CorpGuid,
                            TypeFlag = emp.TypeFlag,
                            AreaCode = emp.AreaCode,
                            TypeFlags = empQualits.TypeFlags,
                            CertificateName = empQualits.CertificateName,
                            CertificateSpecialty = empQualits.CertificateSpecialty,
                            CSCode = empQualits.CSCode,
                            CertificateLevel = empQualits.CertificateLevel,
                            CLCode = empQualits.CLCode,
                            GetCertificateDate = empQualits.GetCertificateDate,
                            Post_psZG = empPosts.Post_psZG,
                            Post_psZGCode = empPosts.Post_psZGCode

                        };
            int empsCount = query.BuildCondition<EmpQueryCondition>(condition).Select(e => e.EmpGuid).Distinct().Count();
            return empsCount;
        }

        /// <summary>
        /// 人员综合统计
        /// </summary>
        /// <param name="flowCode"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override StatisticsStruct GetPersonEmpStatistic(string flowCode, string areaCode)
        {
            string code_list = string.Empty;
            if (!string.IsNullOrEmpty(flowCode))
            {
                code_list = "'" + flowCode.Replace("|", "','") + "'";
            }
            ////取得全部数据源
            List<StatisticsModel> source = new PersonDALWh().GetPersonEmpStatistic(code_list, areaCode);
            ////取得本地人员
            List<StatisticsModel> source1 = source.Where(s => s.AreaCode.StartsWith(areaCode)).ToList();
            ////取得外地人员
            List<StatisticsModel> source2 = source.Where(s => !s.AreaCode.StartsWith(areaCode)).ToList();
            ////取得人员类型
            Dictionary<string, string> classIdList = JsonConvert.DeserializeObject<Dictionary<string, string>>(new BasicBLL().GetSysStaticSettings("PSNCLASSID", areaCode));
            ////取得当前地区
            var areaList = zbdlcontext.AreaSubInfo.Where(a => a.Code == areaCode).OrderBy(a => a.CodeForSort).ToList();
            StatisticsStruct list = new StatisticsStruct();
            ////1、取得标题
            StatisticsStruct.StatisticsHeader header = new StatisticsStruct.StatisticsHeader();
            StatisticsStruct.StatisticsCell hcell1 = new StatisticsStruct.StatisticsCell { Value = "SortCode" };
            StatisticsStruct.StatisticsCell hcell2 = new StatisticsStruct.StatisticsCell { Value = "地区/企业类型" };
            List<StatisticsStruct.StatisticsCell> hcell_list = new List<StatisticsStruct.StatisticsCell>();
            hcell_list.Add(hcell1);
            hcell_list.Add(hcell2);
            foreach (var cl in classIdList)
            {
                StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                cell.Value = cl.Value;
                //cell.Value = cl.Key;
                hcell_list.Add(cell);
            }
            header.HeaderCells = hcell_list.ToArray();
            List<StatisticsStruct.StatisticsHeader> header_list = new List<StatisticsStruct.StatisticsHeader> { header };
            list.Header = header_list.ToArray();
            ////2、取得行
            List<StatisticsStruct.StatisticsRow> row_list = new List<StatisticsStruct.StatisticsRow>();
            //2.1子地区行
            foreach (var area in areaList)
            {
                StatisticsStruct.StatisticsRow row = GetStatisticsRow(source1, classIdList, area.SortCode, area.Title, area.SortCode);
                row_list.Add(row);
            }
            //2.2本地
            StatisticsStruct.StatisticsRow row1 = GetStatisticsRow(source1, classIdList, areaCode + "00", "本地", string.Empty);
            row_list.Add(row1);
            //2.3外地
            StatisticsStruct.StatisticsRow row2 = GetStatisticsRow(source2, classIdList, areaCode + "99", "外地", string.Empty);
            row_list.Add(row2);
            //2.3汇总
            StatisticsStruct.StatisticsRow row3 = GetStatisticsRow(source, classIdList, areaCode, "合计", string.Empty);
            row_list.Add(row3);
            list.Data = row_list.ToArray();
            return list;
        }

        /// <summary>
        /// 人员综合统计-取得单行数据
        /// </summary>
        /// <param name="source"></param>
        /// <param name="classIdList"></param>
        /// <param name="areaCode"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        private StatisticsStruct.StatisticsRow GetStatisticsRow(List<StatisticsModel> source,
            Dictionary<string, string> classIdList, string sortCode, string title, string areaCode)
        {
            int classId = 0;
            int empCount = 0;
            StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
            List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
            StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = sortCode };
            StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = title };
            cell_list.Add(cell1);
            cell_list.Add(cell2);
            foreach (var cl in classIdList)
            {
                StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                if (int.TryParse(cl.Key, out classId))
                {
                    var query = source.Where(s => s.ClassId == classId);
                    if (!string.IsNullOrEmpty(areaCode))
                    {
                        //取得子地区数目
                        empCount = query.Where(s => s.AreaCode == areaCode).Select(s => s.StatisticsCount).FirstOrDefault();
                    }
                    else
                    {
                        //取得统计数
                        empCount = query.Sum(s => s.StatisticsCount);
                    }

                }
                cell.Value = empCount.ToString();
                cell_list.Add(cell);
            }
            row.DataCells = cell_list.ToArray();
            return row;
        }

        /// <summary>
        /// 证书综合统计
        /// </summary>
        /// <param name="flowCode"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override StatisticsStruct GetPersonCertStatistic(string flowCode, string areaCode)
        {
            string code_list = string.Empty;
            if (!string.IsNullOrEmpty(flowCode))
            {
                code_list = "'" + flowCode.Replace("|", "','") + "'";
            }
            ////取得全部数据源
            List<StatisticsModel4> source = new PersonDALWh().GetPersonCertStatistic(code_list, areaCode);
            ////取得证书类型
            IList<T_Sys_Dict> groupIdList = new BasicBLL().GetSysDicts("ZGZSLC", "0");
            Dictionary<string, string> dicList = groupIdList.ToDictionary(c => c.Code, c => c.Name);
            ////取得当前地区
            var areaList = zbdlcontext.AreaSubInfo.Where(a => a.Code == areaCode).OrderBy(a => a.CodeForSort).ToList();
            StatisticsStruct list = new StatisticsStruct();
            ////1、取得标题
            StatisticsStruct.StatisticsHeader header = new StatisticsStruct.StatisticsHeader();
            StatisticsStruct.StatisticsCell hcell1 = new StatisticsStruct.StatisticsCell { Value = "SortCode" };
            StatisticsStruct.StatisticsCell hcell2 = new StatisticsStruct.StatisticsCell { Value = "地区/证书类型" };
            List<StatisticsStruct.StatisticsCell> hcell_list = new List<StatisticsStruct.StatisticsCell>();
            hcell_list.Add(hcell1);
            hcell_list.Add(hcell2);
            foreach (var cl in dicList)
            {
                StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                cell.Value = cl.Value;
                //cell.Value = cl.Key;
                hcell_list.Add(cell);
            }
            header.HeaderCells = hcell_list.ToArray();
            List<StatisticsStruct.StatisticsHeader> header_list = new List<StatisticsStruct.StatisticsHeader> { header };
            list.Header = header_list.ToArray();
            ////2、取得行
            List<StatisticsStruct.StatisticsRow> row_list = new List<StatisticsStruct.StatisticsRow>();
            ////2.1子地区行
            foreach (var area in areaList)
            {
                StatisticsStruct.StatisticsRow row = GetStatisticsRow(source, dicList, area.SortCode, area.Title, area.SortCode);
                row_list.Add(row);
            }
            ////2.2汇总
            StatisticsStruct.StatisticsRow row2 = GetStatisticsRow(source, dicList, areaCode, "合计", string.Empty);
            row_list.Add(row2);
            list.Data = row_list.ToArray();
            return list;
        }

        private StatisticsStruct.StatisticsRow GetStatisticsRow(
         List<StatisticsModel4> source,
         Dictionary<string, string> groupIdList, 
         string sortCode,
         string title, 
         string areaCode)
        {
            int groupId = 0;
            int empCount = 0;
            StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
            List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
            StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = sortCode };
            StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = title };
            cell_list.Add(cell1);
            cell_list.Add(cell2);
            foreach (var cl in groupIdList)
            {
                StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                if (int.TryParse(cl.Key, out groupId))
                {
                    var query = source.Where(s => s.GroupTreeID == groupId);
                    if (!string.IsNullOrEmpty(areaCode))
                    {
                        ////取得子地区数目
                        empCount = query.Where(s => s.AreaCode == areaCode).Select(s => s.StatisticsCount).FirstOrDefault();
                    }
                    else
                    {
                        ////取得统计数
                        empCount = query.Sum(s => s.StatisticsCount);
                    }

                }
                cell.Value = empCount.ToString();
                cell_list.Add(cell);
            }
            row.DataCells = cell_list.ToArray();
            return row;
        }
        
        private StatisticsStruct.StatisticsRow GetStatisticsRow(List<StatisticsModel2> source,
            Dictionary<string, string> flowList, string sortCode, string title, string areaCode)
        {
            StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
            List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
            StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = sortCode };
            StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = title };
            cell_list.Add(cell1);
            cell_list.Add(cell2);
            ////声明临时变量。
            int empCount = 0;
            int index = 2;////空出前面两列。
            Dictionary<string, int> flowListTemp = new Dictionary<string, int>();
            foreach (var fl in flowList)
            {
                var query = source.Where(s => s.FlowCode == fl.Key);
                ////如果是需要合并的列。
                if (flowListTemp.Keys.Contains(fl.Value))
                {
                    int iValue = 0;
                    int.TryParse(cell_list[flowListTemp[fl.Value]].Value, out iValue);
                    empCount = query.Where(s => s.AreaCode.StartsWith(areaCode)).Select(s => s.StatisticsCount).FirstOrDefault();
                    cell_list[flowListTemp[fl.Value]].Value = (iValue + empCount).ToString();
                }
                else
                {
                    StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                    flowListTemp.Add(fl.Value, index);
                    empCount = query.Where(s => s.AreaCode.StartsWith(areaCode)).Select(s => s.StatisticsCount).FirstOrDefault();
                    cell.Value = empCount.ToString();
                    cell_list.Add(cell);
                    index++;
                }
            }

            row.DataCells = cell_list.ToArray();
            return row;
        }

        private StatisticsStruct.StatisticsRow GetPersonExpertStatisticsSum(List<StatisticsModel2> source,
           Dictionary<string, string> flowList, string sortCode, string title, string areaCode)
        {
            int empCount = 0;
            int index = 2;////空出前面两列。
            Dictionary<string, int> flowListTemp = new Dictionary<string, int>();
            StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
            List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
            StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = sortCode };
            StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = title };
            cell_list.Add(cell1);
            cell_list.Add(cell2);
            foreach (var fl in flowList)
            {
                var query = source.Where(s => s.FlowCode == fl.Key);
                ////如果是需要合并的列。
                if (flowListTemp.Keys.Contains(fl.Value))
                {
                    int iValue = 0;
                    int.TryParse(cell_list[flowListTemp[fl.Value]].Value, out iValue);
                    empCount = query.Sum(s => s.StatisticsCount);
                    cell_list[flowListTemp[fl.Value]].Value = (iValue + empCount).ToString();
                }
                else
                {
                    StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                    flowListTemp.Add(fl.Value, index);
                    empCount = query.Sum(s => s.StatisticsCount);
                    cell.Value = empCount.ToString();
                    cell_list.Add(cell);
                    index++;
                }
            }
            row.DataCells = cell_list.ToArray();
            return row;
        }


        #endregion

        #region 职称信息

        /// <summary>
        /// 查询人员职称信息
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override IList<DTO.Tb_Emp_Post> GetEmpEmpPosts(string empGuid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                return null;
            }
            IList<Tb_Emp_Post_Zbdl> EmpPosts = zbdlcontext.Emp_Post.Where(q => q.EmpGuid == eGuid && (q.IsDel == false || q.IsDel == null)).ToList();
            List<DTO.Tb_Emp_Post> list_D = new List<DTO.Tb_Emp_Post>();
            ////实体转换
            foreach (Tb_Emp_Post_Zbdl item in EmpPosts)
            {
                DTO.Tb_Emp_Post post_D = new DTO.Tb_Emp_Post();
                EntityHelper.ConvertEntity2OtherEntity(item, post_D);
                list_D.Add(post_D);
            }
            return list_D;
        }

        /// <summary>
        /// 添加修改职称
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="dbEmp"></param>
        /// <param name="empPosts"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpPostsModif(string corpUserGuid, tb_Emp_Manager_Zbdl dbEmp, IList<DTO.Tb_Emp_Post> empPosts, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            int empPostsCount = zbdlcontext.Emp_Post.Where(p => p.EmpGuid == dbEmp.EmpGuid && (p.IsDel == false || p.IsDel == null)).Count();
            if (empPostsCount == 0)
            {
                result = EmpPostsAdd(corpUserGuid, dbEmp, empPosts, areaCode);
            }
            else
            {
                result = EmpPostsEdit(corpUserGuid, dbEmp, empPosts, areaCode);
            }
            return result;
        }

        /// <summary>
        /// 添加人员职称信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpPostsAdd(string corpUserGuid, tb_Emp_Manager_Zbdl dbEmp, IList<DTO.Tb_Emp_Post> empPosts, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;

            foreach (DTO.Tb_Emp_Post empPost in empPosts)
            {
                if (empPost.Post_psZG == "-1")
                {
                    continue;
                }
                Tb_Emp_Post_Zbdl empPost_E = new Tb_Emp_Post_Zbdl();
                empPost.EmpGuid = dbEmp.EmpGuid;
                empPost.IsDel = false;
                EntityHelper.ConvertEntity2OtherEntity(empPost, empPost_E);
                empPost_E = zbdlcontext.Emp_Post.Add(empPost_E);
                zbdlcontext.SaveChanges();
                result.Message += "人员职称信息添加成功！";
                ////日志
                //var flag = SetUserLog("添加人员职称信息", dbEmp, "03", "1", areaCode, corpUserGuid);
                //if (!flag)
                //{
                //    result.Result = false;
                //    result.Message = "日志写入出错！";
                //    return result;
                //}

            }
            return result;
        }

        /// <summary>
        /// 修改人员职称信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpPostsEdit(string corpUserGuid, tb_Emp_Manager_Zbdl dbEmp, IList<DTO.Tb_Emp_Post> empPosts, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            foreach (DTO.Tb_Emp_Post empPost in empPosts)
            {
                ////修改人员职称信息
                Tb_Emp_Post_Zbdl currenteEmpPost = zbdlcontext.Emp_Post.Where(p => p.EmpGuid == dbEmp.EmpGuid && (p.IsDel == false || p.IsDel == null)).FirstOrDefault();
                if (currenteEmpPost == null)
                {
                    continue;
                }
                if (empPost.Post_psZG == "-1")
                {
                    string empGuid = dbEmp.EmpGuid == null ? "" : dbEmp.EmpGuid.ToString();
                    EmpPostsDel(empGuid, "");
                    continue;
                }
                Tb_Emp_Post_Zbdl empPost_E = new Tb_Emp_Post_Zbdl();
                EntityHelper.ConvertEntity2OtherEntity(empPost, empPost_E);
                EntityHelper.ConvertEntity2Entity<Tb_Emp_Post_Zbdl>(empPost_E, currenteEmpPost);
                zbdlcontext.SaveChanges();
                result.Message += "人员职称信息修改成功！";
                ////日志
                //var flag = SetUserLog("修改人员职称信息", dbEmp, "03", "2", areaCode, corpUserGuid);
                //if (!flag)
                //{
                //    result.Result = false;
                //    result.Message = "日志写入出错！";
                //    return result;
                //}

            }

            return result;
        }

        /// <summary>
        /// 删除职称信息
        /// </summary>
        /// <param name="educationGUID"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpPostsDel(string empGuid, string areaCode)
        {

            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "人员GUID不正确！";
                return result;
            }
            List<Tb_Emp_Post_Zbdl> empPosts = zbdlcontext.Emp_Post.Where(p => p.EmpGuid == eGuid && (p.IsDel == false || p.IsDel == null)).ToList();
            if (empPosts.Count == 0)
            {
                result.Result = false;
                result.Message = "人员没有职称信息！";
                return result;
            }
            foreach (Tb_Emp_Post_Zbdl empPost in empPosts)
            {
                ////逻辑删除
                if (empPost != null)
                {
                    empPost.IsDel = true;
                    zbdlcontext.SaveChanges();
                }
            }
            result.Message = "删除人员职称信息！";
            result.Result = true;
            return result;
        }

        #endregion

        #region 安全考核证

        /// <summary>
        /// 查询人员安全考核证
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override IList<DTO.Tb_Emp_TitleDetailsExt> GetEmpTitleDetailsExt(string empGuid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                return null;
            }
            IList<Tb_Emp_TitleDetailsExt_Zbdl> qualities = zbdlcontext.Emp_TitleDetailsExt.Where(q => q.EmpGuid == eGuid && (q.IsDel == false || q.IsDel == null)).ToList();
            List<DTO.Tb_Emp_TitleDetailsExt> list_D = new List<DTO.Tb_Emp_TitleDetailsExt>();
            ////实体转换
            foreach (Tb_Emp_TitleDetailsExt_Zbdl item in qualities)
            {
                DTO.Tb_Emp_TitleDetailsExt details_D = new DTO.Tb_Emp_TitleDetailsExt();
                EntityHelper.ConvertEntity2OtherEntity(item, details_D);
                list_D.Add(details_D);
            }
            return list_D;
        }

        /// <summary>
        /// 添加修改安全考核证
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="dbEmp"></param>
        /// <param name="empQualities"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpTitleDetailsExtModif(string corpUserGuid, tb_Emp_Manager_Zbdl dbEmp, IList<DTO.Tb_Emp_TitleDetailsExt> empQualities, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            int empQualitiesCount = zbdlcontext.Emp_TitleDetailsExt.Where(p => p.EmpGuid == dbEmp.EmpGuid && (p.IsDel == false || p.IsDel == null)).Count();
            if (empQualitiesCount == 0)
            {
                result = EmpTitleDetailsExtAdd(corpUserGuid, dbEmp, empQualities, areaCode);
            }
            else
            {
                result = EmpTitleDetailsExtEdit(corpUserGuid, dbEmp, empQualities, areaCode);
            }
            return result;
        }
        /// <summary>
        /// 判断是否有重复项
        /// </summary>
        /// <param name="empQualitie"></param>
        /// <param name="IDCard"></param>
        /// <param name="isEdit"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpTitleDetailsExtIsExist(DTO.Tb_Emp_TitleDetailsExt empQualitie, string IDCard)
        {
            var query = from qualitie in zbdlcontext.Emp_TitleDetailsExt
                        join manager in zbdlcontext.Emp_Manager
                        on qualitie.EmpGuid equals manager.EmpGuid
                        where (qualitie.IsDel == null || qualitie.IsDel == false) && (manager.IsDel == null || manager.IsDel == false)
                        select new { qualitie.EducationGUID, qualitie.CertificateCode, manager.IDCard };
            ////判断是否重复       
            int count = query.Where(q => q.CertificateCode == empQualitie.CertificateCode && q.IDCard != IDCard).Count();

            DTO.OperationResult result = new OperationResult();
            if (count == 0)
            {
                result.Result = true;
            }
            else
            {
                result.Result = false;
            }
            return result;
        }
        /// <summary>
        /// 添加人员安全考核证
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpTitleDetailsExtAdd(string corpUserGuid, tb_Emp_Manager_Zbdl dbEmp, IList<DTO.Tb_Emp_TitleDetailsExt> empQualities, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;

            foreach (DTO.Tb_Emp_TitleDetailsExt empQualitie in empQualities)
            {
                if (string.IsNullOrEmpty(empQualitie.CertificateCode))
                {
                    continue;
                }
                ////判断是否重复
                result = EmpTitleDetailsExtIsExist(empQualitie, dbEmp.IDCard);
                if (!result.Result)
                {
                    result.Result = false;
                    result.Message += "编号为 [" + empQualitie.CertificateCode + "] 的安全考核证已存在，添加失败！";
                    continue;
                }
                empQualitie.EmpGuid = dbEmp.EmpGuid;
                // empQualitie.EducationGUID = Guid.NewGuid();
                empQualitie.IsDel = false;
                empQualitie.EmpType = "A";
                if (dbEmp.TypeFlag == "-1")
                {
                    empQualitie.EmpType = "B";
                }
                empQualitie.ZsRegisterDate = DateTime.Now.ToString();
                Tb_Emp_TitleDetailsExt_Zbdl empQuality_E = new Tb_Emp_TitleDetailsExt_Zbdl();
                EntityHelper.ConvertEntity2OtherEntity(empQualitie, empQuality_E);
                empQuality_E = zbdlcontext.Emp_TitleDetailsExt.Add(empQuality_E);
                zbdlcontext.SaveChanges();
                result.Message += "编号为 [" + empQualitie.CertificateCode + "] 的安全考核证添加成功！";
            }
            return result;
        }

        /// <summary>
        /// 修改安全考核证
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpTitleDetailsExtEdit(string corpUserGuid, tb_Emp_Manager_Zbdl dbEmp, IList<DTO.Tb_Emp_TitleDetailsExt> empQualities, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            foreach (DTO.Tb_Emp_TitleDetailsExt empQualitie in empQualities)
            {
                ////判断是否重复
                result = EmpTitleDetailsExtIsExist(empQualitie, dbEmp.IDCard);
                if (!result.Result)
                {
                    result.Result = false;
                    result.Message += "编号为 [" + empQualitie.CertificateCode + "] 的安全考核证已存在，修改失败！";
                    continue;
                }
                ////实体转换
                Tb_Emp_TitleDetailsExt_Zbdl empquality = zbdlcontext.Emp_TitleDetailsExt.Where(q => q.EmpGuid == dbEmp.EmpGuid && (q.IsDel == false || q.IsDel == null)).FirstOrDefault();
                if (empquality == null)
                {
                    continue;
                }
                Tb_Emp_TitleDetailsExt_Zbdl empQuality_E = new Tb_Emp_TitleDetailsExt_Zbdl();
                EntityHelper.ConvertEntity2OtherEntity(empQualitie, empQuality_E);
                EntityHelper.ConvertEntity2Entity<Tb_Emp_TitleDetailsExt_Zbdl>(empQuality_E, empquality);
                zbdlcontext.SaveChanges();
                result.Message += "编号为 [" + empQualitie.CertificateCode + "] 的安全考核证修改成功！";
            }

            return result;
        }

        /// <summary>
        /// 删除安全考核证
        /// </summary>
        /// <param name="educationGUID"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpTitleDetailsExtDel(string empGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "人员GUID不正确！";
                return result;
            }
            List<Tb_Emp_TitleDetailsExt_Zbdl> empQualities = zbdlcontext.Emp_TitleDetailsExt.Where(p => p.EmpGuid == eGuid && (p.IsDel == false || p.IsDel == null)).ToList();
            if (empQualities.Count == 0)
            {
                result.Result = false;
                result.Message = "人员没有安全考核证！";
                return result;
            }
            foreach (Tb_Emp_TitleDetailsExt_Zbdl empQualitie in empQualities)
            {
                ////逻辑删除
                if (empQualitie != null)
                {
                    empQualitie.IsDel = true;
                }
                zbdlcontext.SaveChanges();
            }
            result.Message = "删除人员安全考核证！";
            result.Result = true;
            return result;
        }

        #endregion

        #region 人员资格证书

        /// <summary>
        /// 取得证书编号格式
        /// </summary>
        /// <param name="code"></param>
        /// <param name="typeFlags"></param>
        /// <param name="certLevel"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.T_Sys_CodeValidation GetQualityCodeValid(string code, string typeFlags, string certLevel, string areaCode)
        {
            var item = zbdlcontext.T_Sys_CodeValidation.Where(t => t.Code == code && t.TypeFlags == typeFlags && t.CertLevel == certLevel && t.IsDel == false).FirstOrDefault();
            DTO.T_Sys_CodeValidation item_D = new DTO.T_Sys_CodeValidation();
            if (item != null)
            {
                EntityHelper.ConvertEntity2OtherEntity(item, item_D);
            }
            return item_D;
        }
        /// <summary>
        /// 验证证书编号格式
        /// </summary>
        /// <param name="code"></param>
        /// <param name="typeFlags"></param>
        /// <param name="certLevel"></param>
        /// <param name="certCode"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CheckQualityCodeValid(string code, string typeFlags, string certLevel, string certCode, string areaCode)
        {
            DTO.OperationResult result = new OperationResult();
            result.Result = true;
            if (string.IsNullOrEmpty(certCode))
            {
                result.Result = false;
                return result;
            }
            //取得验证规则
            var CodeValid = GetQualityCodeValid(code, typeFlags, certLevel, areaCode);
            if (CodeValid == null)
            {
                return result;
            }
            if (CodeValid.RegExpress != null)
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^" + CodeValid.RegExpress + "$");
                //根据验证表达式验证数据
                if (!reg.IsMatch(certCode))
                {
                    result.Result = false;
                    return result;
                }
            }
            return result;
        }
        /// <summary>
        /// 判断人员资格证书是否存在
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckQualityIsExist(string cartGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(cartGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "证书GUID不正确！";
                return result;
            }
            ////查询人员
            var empQualitie = zbdlcontext.Emp_Qualities.SingleOrDefault(q => q.EducationGUID == eGuid && (q.IsDel == false || q.IsDel == null));
            if (empQualitie == null)
            {
                result.Result = false;
                result.Message = "证书信息不存在！";
                return result;
            }
            result.Result = true;
            result.ReturnValue = empQualitie;
            return result;
        }

        /// <summary>
        /// 判断证书是否重复
        /// </summary>
        /// <param name="empQualitie"></param>
        /// <param name="IDCard"></param>
        /// <param name="isEdit"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpTitleDetailsIsExist(DTO.Tb_Emp_TitleDetails empQualitie, string IDCard, bool isEdit, int? classId)
        {
            var query = from qualitie in zbdlcontext.Emp_Qualities
                        join manager in zbdlcontext.Emp_Manager
                        on qualitie.EmpGuid equals manager.EmpGuid
                        where (qualitie.IsDel == null || qualitie.IsDel == false) && (manager.IsDel == null || manager.IsDel == false)
                        select new { qualitie.EducationGUID, qualitie.CertificateCode, qualitie.CertificateSpecialty, manager.IDCard, manager.ClassId };
            ////判断是否重复
            string specialty = empQualitie.CertificateSpecialty == null ? "" : empQualitie.CertificateSpecialty.ToString();
            //不同身份证的人是否存在证书
            int count = query.Where(q => q.CertificateCode == empQualitie.CertificateCode && q.IDCard != IDCard).Count();
            //统一身份证同证书号同专业是否存
            query = query.Where(q => q.CertificateCode == empQualitie.CertificateCode && q.CertificateSpecialty == specialty && q.IDCard == IDCard && q.ClassId == classId);
            if (isEdit)
            {
                //修改证书
                query = query.Where(q => q.EducationGUID != empQualitie.EducationGUID);
            }
            int count1 = query.Count();
            DTO.OperationResult result = new OperationResult();
            if (count == 0 && count1 == 0)
            {
                result.Result = true;
            }
            else
            {
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 导入证书不能重复添加
        /// </summary>
        /// <param name="empQualitie"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpTitleDetailsIsExist(DTO.Tb_Emp_TitleDetails empQualitie)
        {
            var qualities = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == empQualitie.EmpGuid && q.IsValid == 100 && q.TypeFlags == empQualitie.TypeFlags && q.CertificateLevel == empQualitie.CertificateLevel && (q.IsDel == false || q.IsDel == null)).Count();

            DTO.OperationResult result = new OperationResult();
            if (qualities == 0)
            {
                result.Result = true;
            }
            else
            {
                result.Result = false;
                result.Message = "证书已经从省注册中心导入，不能再添加！";
            }
            return result;
        }
        /// <summary>
        /// 取得证书类别审核状态codetype
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="stampCode"></param>
        /// <returns></returns>
        private int GetEmpCertManual(string classId, string stampCode)
        {
            string codeType = classId.Trim() + "01";//人员执业手册
            if (stampCode.Trim() == "ZGZS")
            {
                codeType = classId.Trim() + "02";//人员资格证书
            }
            if (stampCode.Trim() == "ZGZS-Expert")
            {
                codeType = classId.Trim() + "03";//人员资格证书
            }
            return int.Parse(codeType);
        }
        /// <summary>
        /// 判断是否显示人员执业手册
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="zgzs"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CheckEmpManualIsExist(string corpGuid, string empGuid, string zgzs, string areaCode)
        {
            Guid guidTmp = Guid.Empty;
            DTO.OperationResult result = new DTO.OperationResult();
            //人员是否存在
            DTO.OperationResult result0 = CheckEmpIsExist(empGuid);
            if (result0.Result)
            {
                tb_Emp_Manager_Zbdl emp = (tb_Emp_Manager_Zbdl)result0.ReturnValue;
                guidTmp = emp.CorpGuid;
            }
            else
            {
                if (!Guid.TryParse(corpGuid, out guidTmp))
                {
                    result.Result = false;
                    return result;
                }
            }
            ////取得所属企业角色
            int? roleId = zbdlcontext.T_Sys_Users.Where(u => u.UserGuid == guidTmp).Select(u => u.RoleID).FirstOrDefault();
            if (roleId == null)
            {
                result.Result = false;
                return result;
            }
            ////执业手册标识：字符ZGZS+两位地区号+“-”+企业RoleID
            string ZYZS = zgzs + areaCode.Substring(0, 2) + "-" + roleId.ToString();
            ////字典表中存在数据显示列表
            int count = new BasicBLL().GetQualitiesDic(ZYZS, "0").Count();
            if (count == 0)
            {
                result.Result = false;
                return result;
            }
            result.Result = true;
            result.ReturnValue = ZYZS;
            return result;

        }

        /// <summary>
        /// 查询人员资格证书证书
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override string GetEmpQualities(string empGuid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                return string.Empty;
            }
            var qualities = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == eGuid && (q.IsDel == false || q.IsDel == null));

            //if (!string.IsNullOrEmpty(groupId))
            //{
            //    int groupTreeID = 0;
            //    int.TryParse(groupId,out groupTreeID);
            //    qualities = qualities.Where(q => q.GroupTreeID == groupTreeID);
            //}

            List<DTO.Tb_Emp_TitleDetails> list_D = new List<DTO.Tb_Emp_TitleDetails>();
            ////实体转换
            foreach (Tb_Emp_TitleDetails_Zbdl item in qualities)
            {
                DTO.Tb_Emp_TitleDetails item_D = new DTO.Tb_Emp_TitleDetails();
                EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                item_D.StrFlowCode = GetFlowCodeTitle(item_D.FlowCode, item_D.ClassID == null ? "2611" : item_D.ClassID.ToString(), areaCode);
                list_D.Add(item_D);
            }
            return JsonConvert.SerializeObject(list_D).Replace(" ", "");

        }

        /// <summary>
        /// 根据groupId查询人员资格证书证书
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override string GetEmpQualitiesByGroupId(string empGuid, string areaCode, string groupId)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                return string.Empty;
            }
            var qualities = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == eGuid && (q.IsDel == false || q.IsDel == null));

            if (!string.IsNullOrEmpty(groupId))
            {
                int groupTreeID = 0;
                int.TryParse(groupId, out groupTreeID);
                qualities = qualities.Where(q => q.GroupTreeID == groupTreeID);
            }

            List<DTO.Tb_Emp_TitleDetails> list_D = new List<DTO.Tb_Emp_TitleDetails>();
            ////实体转换
            foreach (Tb_Emp_TitleDetails_Zbdl item in qualities)
            {
                DTO.Tb_Emp_TitleDetails item_D = new DTO.Tb_Emp_TitleDetails();
                EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                item_D.StrFlowCode = GetFlowCodeTitle(item_D.FlowCode, item_D.ClassID == null ? "2611" : item_D.ClassID.ToString(), areaCode);
                list_D.Add(item_D);
            }
            return JsonConvert.SerializeObject(list_D).Replace(" ", "");

        }

        /// <summary>
        /// 添加人员资格证书证书
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityAdd(string corpUserGuid, string empGuid, IList<DTO.Tb_Emp_TitleDetails> empQualities, bool isReturnModel, string areaCode)
        {
            ////判断人员状态
            //DTO.OperationResult result = CheckEmpStasus(empGuid, string.Empty, 1, areaCode);
            //if (!result.Result)
            //{
            //    return result;
            //}
            ////判断人员是否存在
            DTO.OperationResult result = CheckEmpIsExist(empGuid);
            if (!result.Result)
            {
                return result;
            }
            string title = "人员执业手册";
            try
            {
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                foreach (DTO.Tb_Emp_TitleDetails empQualitie in empQualities)
                {
                    ////职业手册or资格证书
                    if (empQualitie.StampCode.Trim() == "ZGZS")
                    {
                        title = "人员资格证书";
                    }
                    if (empQualitie.StampCode.Trim() == "ZGZSLC")
                    {
                        title = "人员资格证书";
                    }
                    if (empQualitie.StampCode.Trim() == "ZGZS-Expert")
                    {
                        title = "执业注册证书";
                    }
                    ////已导入证书类别不能再添加
                    DTO.OperationResult result3 = EmpTitleDetailsIsExist(empQualitie);
                    if (!result3.Result)
                    {
                        result.Result = false;
                        result.Message += "[" + empQualitie.CertificateName + "]" + result3.Message;
                        continue;
                    }
                    ////判断是否重复
                    DTO.OperationResult result0 = EmpTitleDetailsIsExist(empQualitie, currentManager.IDCard, false, currentManager.ClassId);
                    if (!result0.Result)
                    {
                        result.Result = false;
                        result.Message += "证书编号 [" + empQualitie.CertificateCode + "] 已存在添加失败！";
                        continue;
                    }
                    //验证编号格式
                    DTO.OperationResult result1 = CheckQualityCodeValid("EmpTitleDetails", empQualitie.TypeFlags.ToString(), empQualitie.CertificateLevel, empQualitie.CertificateCode, areaCode);
                    if (!result1.Result)
                    {
                        result.Result = false;
                        result.Message += "证书编号 [" + empQualitie.CertificateCode + "] 格式不正确！";
                        continue;
                    }
                    //添加证书
                    Tb_Emp_TitleDetails_Zbdl empQuality_E = new Tb_Emp_TitleDetails_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(empQualitie, empQuality_E);
                    empQuality_E.EmpGuid = currentManager.EmpGuid;
                    if (empQuality_E.EducationGUID == Guid.Empty)
                    {
                        empQuality_E.EducationGUID = Guid.NewGuid();
                    }
                    empQuality_E.IsDel = false;
                    empQuality_E.FlowCode = "0";
                    empQuality_E.ZsRegisterDate = DateTime.Now.ToString();
                    empQuality_E = zbdlcontext.Emp_Qualities.Add(empQuality_E);
                    zbdlcontext.SaveChanges();
                    ////判断人员状态,审核后添加的数据增加tb_flowcode状态值
                    int flowCode = zbdlcontext.FlowCodes.Where(f => f.ObjectId == empGuid && f.CodeType == currentManager.ClassId && (f.IsDel == false || f.IsDel == null) && f.FlowCode.Contains("1,")).Count();
                    if (flowCode > 0)
                    {
                        EmpFlowCode(empQuality_E.EducationGUID.ToString(), GetEmpCertManual(currentManager.ClassId.ToString(), empQualitie.StampCode), areaCode);
                    }
                    result.Message += title + empQualitie.CertificateCode + "添加成功！";
                    ////日志
                    var flag = SetUserLog("添加" + title, currentManager, "02", "1", areaCode, corpUserGuid);
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message = "日志写入出错！";
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = title + "添加失败" + ex.Message;
                result.Result = false;
            }
            result.ReturnValue = null;
            return result;
        }

        /// <summary>
        /// 企业为人员变更资格证书
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityEdit(string corpUserGuid, string empGuid, IList<DTO.Tb_Emp_TitleDetails> empQualities, string areaCode)
        {
            ////判断人员状态
            bool delStatus = false;
            DTO.OperationResult result = CheckEmpStasus(empGuid, string.Empty, 4, areaCode);
            if (!result.Result)
            {
                delStatus = true;//人员已上报审核
            }
            result.Message = "";
            string title = "人员执业手册";
            try
            {
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                foreach (DTO.Tb_Emp_TitleDetails empQualitie in empQualities)
                {
                    //人员执业手册
                    if (empQualitie.StampCode.Trim() == "ZGZS")
                    {
                        title = "人员资格证书";
                    }
                    if (empQualitie.StampCode.Trim() == "ZGZS-Expert")
                    {
                        title = "执业注册证书";
                    }
                    ////判断是否重复
                    DTO.OperationResult result0 = EmpTitleDetailsIsExist(empQualitie, currentManager.IDCard, true, currentManager.ClassId);
                    if (!result0.Result)
                    {
                        result.Result = false;
                        result.Message += "证书编号" + empQualitie.CertificateCode + "已存在修改失败！";
                        continue;
                    }
                    //验证编号格式
                    DTO.OperationResult result1 = CheckQualityCodeValid("EmpTitleDetails", empQualitie.TypeFlags.ToString(), empQualitie.CertificateLevel, empQualitie.CertificateCode, areaCode);
                    if (!result1.Result)
                    {
                        result.Result = false;
                        result.Message += "证书编号 [" + empQualitie.CertificateCode + "] 格式不正确！";
                        continue;
                    }
                    ///判断证书审核状态
                    if (delStatus)
                    {
                        var results = CheckSubFlowCode(empQualitie.EducationGUID.ToString(), 4, GetEmpCertManual(currentManager.ClassId.ToString(), empQualitie.StampCode), corpUserGuid);
                        if (!results.Result)
                        {
                            result.Message += results.Message;
                            continue;
                        }
                    }
                    ////已导入证书类别不能再添加
                    DTO.OperationResult result3 = EmpTitleDetailsIsExist(empQualitie);
                    if (!result3.Result)
                    {
                        result.Result = false;
                        result.Message += "[" + empQualitie.CertificateName + "]" + result3.Message;
                        continue;
                    }
                    ////修改证书
                    Tb_Emp_TitleDetails_Zbdl empquality = zbdlcontext.Emp_Qualities.SingleOrDefault(q => q.EducationGUID == empQualitie.EducationGUID);
                    if (empquality == null)
                    {
                        continue;
                    }
                    Tb_Emp_TitleDetails_Zbdl empQuality_E = new Tb_Emp_TitleDetails_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(empQualitie, empQuality_E);
                    if (empQualitie.IsValid != null && empQualitie.IsValid == 100)
                    {
                        empQuality_E.CertificateCode = empquality.CertificateCode;
                        empQuality_E.CertificateName = empquality.CertificateName;
                        empQuality_E.CertificateLevel = empquality.CertificateLevel;
                        empQuality_E.CLCode = empquality.CLCode;
                        empQuality_E.CSCode = empquality.CSCode;
                        empQuality_E.CertificateSpecialty = empquality.CertificateSpecialty;
                        empQuality_E.TypeFlags = empquality.TypeFlags;
                        empQuality_E.RegisterCorpName = empquality.RegisterCorpName;
                    }
                    EntityHelper.ConvertEntity2Entity<Tb_Emp_TitleDetails_Zbdl>(empQuality_E, empquality);
                    zbdlcontext.SaveChanges();
                    result.Message += title + empQualitie.CertificateCode + "修改成功！";
                    ////日志
                    var flag = SetUserLog("修改" + title, currentManager, "02", "2", areaCode, corpUserGuid);
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message = "日志写入出错！";
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = title + "修改失败：" + ex.Message;
                result.Result = false;
            }
            result.ReturnValue = null;
            return result;
        }
        /// <summary>
        /// 删除人员资格证书多项
        /// </summary>
        /// <param name="educationGUID"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityMultiDel(string educationGUIDs, string empGuid, string areaCode)
        {
            ////判断人员状态
            bool delStatus = false;
            DTO.OperationResult result = CheckEmpStasus(empGuid, string.Empty, 4, areaCode);
            if (!result.Result)
            {
                delStatus = true;//人员已上报审核
            }
            result.Message = "";
            string title = "人员资格证书";
            try
            {
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                Guid eduguid = Guid.Empty;
                string[] educationGUID = educationGUIDs.Split(',');
                foreach (string eduGuid in educationGUID)
                {
                    Guid.TryParse(eduGuid, out eduguid);
                    Tb_Emp_TitleDetails_Zbdl dbEmpQuality = zbdlcontext.Emp_Qualities.Where(p => p.EducationGUID == eduguid && (p.IsDel == false || p.IsDel == null)).FirstOrDefault();
                    ////逻辑删除
                    if (dbEmpQuality == null)
                    {
                        continue;
                    }
                    if (dbEmpQuality.IsValid != null && dbEmpQuality.IsValid == 100)
                    {
                        result.Message += title + "[" + dbEmpQuality.CertificateName + "]" + "是系统导入证书，不能删除！";
                        continue;
                    }
                    OperationResult ret = GetCertFlowCode(currentManager.CorpGuid.ToString(), dbEmpQuality.EducationGUID.ToString(), 7, areaCode);
                    if (!ret.Result)
                    {
                        continue;
                    }
                    List<DTO.OperationResult> flowList = (List<DTO.OperationResult>)ret.ReturnValue;
                    if (!flowList[2].Result)
                    {
                        result.Message += title + "已处于审核过程中，不可删除";
                        continue;
                    }
                    //人员执业手册
                    if (dbEmpQuality.StampCode.Trim() != "ZGZS")
                    {
                        title = "人员执业手册";
                    }
                    ///判断证书审核状态
                    if (delStatus)
                    {
                        var results = CheckSubFlowCode(eduGuid, 4, GetEmpCertManual(currentManager.ClassId.ToString(), dbEmpQuality.StampCode), currentManager.CorpGuid.ToString());
                        if (!results.Result)
                        {
                            result.Message += title + "[" + dbEmpQuality.CertificateName + "]" + "已上报审核，不能删除！";
                            continue;
                        }
                    }
                    dbEmpQuality.IsDel = true;
                    zbdlcontext.SaveChanges();
                    result.Message += "删除[" + dbEmpQuality.CertificateName + "]" + title + "成功！";
                    result.Result = true;
                    ////2.日志
                    var flag = SetUserLog("删除" + title, currentManager, "02", "3", areaCode, currentManager.CorpGuid.ToString());
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message = "日志写入出错！";
                        return result;
                    }

                }
                if (string.IsNullOrEmpty(result.Message))
                {
                    result.Result = false;
                    result.Message = title + "不存在！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = title + "删除失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }

        /// <summary>
        /// 删除人员所有资格证书
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult EmpQualitysDel(string empGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "人员GUID不正确！";
                return result;
            }
            List<Tb_Emp_TitleDetails_Zbdl> empQualities = zbdlcontext.Emp_Qualities.Where(p => p.EmpGuid == eGuid && (p.IsDel == false || p.IsDel == null)).ToList();
            if (empQualities.Count == 0)
            {
                result.Result = false;
                result.Message = "人员没有资格证书和执业手册！";
                return result;
            }
            foreach (Tb_Emp_TitleDetails_Zbdl empQualitie in empQualities)
            {
                ////逻辑删除
                if (empQualitie != null)
                {
                    empQualitie.IsDel = true;
                }
                zbdlcontext.SaveChanges();
            }

            result.Message = "删除人员所有资格证书和执业手册！";
            result.Result = true;
            return result;
        }

        #endregion

        #region 工作经历
        /// <summary>
        /// 人员主要工作经历查询
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override IList<DTO.tb_WorkExperience> GetWorkExperienceList(string empGuid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                return null;
            }
            var list = zbdlcontext.WorkExperience.Where(q => q.EmpGuid == eGuid && (q.IsDel == false || q.IsDel == null)).OrderByDescending(q => q.BeginDate).ThenByDescending(q => q.EndDate).ToList();
            List<DTO.tb_WorkExperience> list_D = new List<DTO.tb_WorkExperience>();
            ////实体转换
            foreach (tb_WorkExperience_Zbdl item in list)
            {
                DTO.tb_WorkExperience work_D = new DTO.tb_WorkExperience();
                EntityHelper.ConvertEntity2OtherEntity(item, work_D);
                list_D.Add(work_D);
            }
            return list_D;
        }

        /// <summary>
        /// 人员主要工作经历添加
        /// </summary>
        /// <param name="workExp"></param>
        /// <returns></returns>
        public override DTO.OperationResult WorkExperienceAdd(DTO.tb_WorkExperience workExp, string areaCode)
        {
            ////判断人员状态
            DTO.OperationResult result = CheckEmpStasus(workExp.EmpGuid.ToString(), string.Empty, 1, areaCode);
            if (!result.Result)
            {
                return result;
            }
            try
            {
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                ////添加人员主要工作经历
                tb_WorkExperience_Zbdl work_E = new tb_WorkExperience_Zbdl();
                EntityHelper.ConvertEntity2OtherEntity(workExp, work_E);
                work_E.IsDel = false;
                work_E = zbdlcontext.WorkExperience.Add(work_E);
                zbdlcontext.SaveChanges();
                result.Result = true;
                result.Message = "人员主要工作经历添加成功！";
                ////日志
                var flag = SetUserLog("添加人员主要工作经历", currentManager, "04", "1", areaCode, currentManager.CorpGuid.ToString());
                if (!flag)
                {
                    result.Result = false;
                    result.Message = "日志写入出错！";
                    return result;
                }

            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "人员主要工作经历添加失败" + ex.Message;
                result.Result = false;
            }
            result.ReturnValue = null;
            return result;
        }

        /// <summary>
        /// 人员主要工作经历修改
        /// </summary>
        /// <param name="workExp"></param>
        /// <returns></returns>
        public override DTO.OperationResult WorkExperienceEdit(DTO.tb_WorkExperience workExp, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            tb_WorkExperience_Zbdl currentWorkExp = zbdlcontext.WorkExperience.Where(p => p.EmpGuid == workExp.EmpGuid && p.ID == workExp.ID).FirstOrDefault();
            if (currentWorkExp == null)
            {
                result.Message = "人员主要工作经历不存在！";
                result.Result = false;
                return result;
            }
            ////判断人员状态
            result = CheckEmpStasus(workExp.EmpGuid.ToString(), string.Empty, 1, areaCode);
            if (!result.Result)
            {
                return result;
            }
            try
            {
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                ////实体转换
                tb_WorkExperience_Zbdl workExp_E = new tb_WorkExperience_Zbdl();
                EntityHelper.ConvertEntity2OtherEntity(workExp, workExp_E);
                EntityHelper.ConvertEntity2Entity<tb_WorkExperience_Zbdl>(workExp_E, currentWorkExp);
                zbdlcontext.SaveChanges();
                result.Message = "修改人员主要工作经历成功！";
                result.Result = true;

                ////日志
                var flag = SetUserLog("修改人员主要工作经历", currentManager, "04", "2", areaCode, currentManager.CorpGuid.ToString());
                if (!flag)
                {
                    result.Result = false;
                    result.Message = "日志写入出错！";
                    return result;
                }

            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "修改人员主要工作经历失败：" + ex.Message;
                result.Result = false;
            }
            result.ReturnValue = null;
            return result;
        }

        /// <summary>
        /// 人员主要工作经历删除
        /// </summary>
        /// <param name="workExp"></param>
        /// <returns></returns>
        public override DTO.OperationResult WorkExperienceDel(string workExpId, string empGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (string.IsNullOrEmpty(workExpId))
            {
                result.Result = false;
                result.Message = "人员工作经历参数不正确！";
                return result;
            }
            ////判断人员状态
            result = CheckEmpStasus(empGuid, string.Empty, 1, areaCode);
            if (!result.Result)
            {
                return result;
            }
            try
            {
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                string[] workExpIds = workExpId.Split(',');
                int id = 0;
                foreach (string workId in workExpIds)
                {
                    if (!int.TryParse(workId, out id))
                    {
                        continue;
                    }
                    tb_WorkExperience_Zbdl currentWorkExp = zbdlcontext.WorkExperience.Where(p => p.ID == id).FirstOrDefault();
                    if (currentWorkExp == null)
                    {
                        continue;
                    }
                    ////逻辑删除
                    currentWorkExp.IsDel = true;
                    zbdlcontext.SaveChanges();
                    result.Message += "删除 [" + currentWorkExp.Post + "] 工作经历成功！";
                    result.Result = true;
                    ////日志
                    var flag = SetUserLog("删除人员主要工作经历", currentManager, "04", "3", areaCode, currentManager.CorpGuid.ToString());
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message = "日志写入出错！";
                        return result;
                    }

                }
                if (string.IsNullOrEmpty(result.Message))
                {
                    result.Result = false;
                    result.Message = "人员工作经历不存在！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "删除人员主要工作经历失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 删除人员所有主要工作经历
        /// </summary>
        /// <param name="workExp"></param>
        /// <returns></returns>
        private DTO.OperationResult WorkExperiencesDel(string empGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "人员GUID不正确！";
                return result;
            }
            List<tb_WorkExperience_Zbdl> currentWorkExps = zbdlcontext.WorkExperience.Where(p => p.EmpGuid == eGuid && (p.IsDel == false || p.IsDel == null)).ToList();
            if (currentWorkExps.Count == 0)
            {
                result.Result = false;
                result.Message = "人员没有工作经历！";
                return result;
            }
            foreach (tb_WorkExperience_Zbdl currentWorkExp in currentWorkExps)
            {
                ////逻辑删除
                if (currentWorkExp != null)
                {
                    currentWorkExp.IsDel = true;
                }
                zbdlcontext.SaveChanges();
            }
            result.Message = "删除人员所有工作经历成功！";
            result.Result = true;
            return result;
        }

        #endregion

        #region 查询操作日志
        /// <summary>
        /// 取得分页日志列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="objectId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<User_Log> GetUserLogList(int pageCount, int pageSize, string objectId, string userRole, string areaCode)
        {
            Guid empGuid = Guid.Empty;
            if (!Guid.TryParse(objectId, out empGuid))
            {
                return null;
            }
            var query = loghelper.GetUserLog(objectId, null, areaCode);
            if (!string.IsNullOrEmpty(userRole))
            {
                if (userRole.ToLower() == "manager")
                {
                    return query.Where(u => int.Parse(u.FunctionId) >= 4).OrderByDescending(u => u.IsrtDate).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
                }
            }
            return query.OrderByDescending(u => u.IsrtDate).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 返回日志数
        /// </summary>
        /// <param name="objectId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetUserLogCount(string objectId, string userRole, string areaCode)
        {
            Guid empGuid = Guid.Empty;
            if (!Guid.TryParse(objectId, out empGuid))
            {
                return 0;
            }
            var query = loghelper.GetUserLog(objectId, null, areaCode);
            if (!string.IsNullOrEmpty(userRole))
            {
                if (userRole.ToLower() == "manager")
                {
                    return query.Where(u => int.Parse(u.FunctionId) >= 4).Count();
                }
            }
            return query.Count();
        }

        /// <summary>
        /// 查询操作日志
        /// </summary>
        /// <param name="objectId">对象唯一标识</param>
        /// <param name="codeType">业务标识</param>
        /// <param name="areaCode">市场范围地区</param>
        /// <returns></returns>
        public override IList<User_Log> GetUserLog(string objectId, string areaCode)
        {
            Guid empGuid = Guid.Empty;
            if (!Guid.TryParse(objectId, out empGuid))
            {
                return null;
            }
            return loghelper.GetUserLog(objectId, null, areaCode);

        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="empGuid"></param>
        /// <param name="classID"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        private bool SetUserLog(string message, tb_Emp_Manager_Zbdl currentManager, string classID, string type, string areaCode, string corpUserGuid)
        {
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result)
            {
                return false;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            loghelper.InsertDetailUserLog(message, currentManager.EmpGuid.ToString(), currentManager.ClassId.ToString() + classID, type, new User_Log()
            {
                IsrtDate = DateTime.Now,
                IsrtUserArea = areaCode,
                IsrtUser = userInfo.UserGuid.ToString(),
                IsrtUserName = userInfo.Name,
                IsrtUserRole = userInfo.RoleID.ToString()
            });
            return true;
        }

        /// <summary>
        /// 人员证书日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="empGuid"></param>
        /// <param name="classID"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        private bool SetUserCertLog(string message, Tb_Emp_TitleDetails_Zbdl currentCert, string classID, string type, string areaCode, string corpUserGuid)
        {
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result)
            {
                return false;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            loghelper.InsertDetailUserLog(message, currentCert.EducationGUID.ToString(), classID, type, new User_Log()
            {
                IsrtDate = DateTime.Now,
                IsrtUserArea = areaCode,
                IsrtUser = userInfo.UserGuid.ToString(),
                IsrtUserName = userInfo.Name,
                IsrtUserRole = userInfo.RoleID.ToString()
            });
            return true;
        }

        /// <summary>
        /// 人员职称日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="empGuid"></param>
        /// <param name="classID"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        private bool SetUserPostLog(string message, Tb_Emp_Post_Zbdl currentPost, string classID, string type, string areaCode, string corpUserGuid)
        {
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result)
            {
                return false;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            loghelper.InsertDetailUserLog(message, currentPost.EmpGuid.ToString(), classID, type, new User_Log()
            {
                IsrtDate = DateTime.Now,
                IsrtUserArea = areaCode,
                IsrtUser = userInfo.UserGuid.ToString(),
                IsrtUserName = userInfo.Name,
                IsrtUserRole = userInfo.RoleID.ToString()
            });
            return true;
        }
        
        
        #endregion

        #region 判断管理人员审核状态 2013-10-19 毛凯
        /// <summary>
        /// 人员即是管理人员又是从业人员审核状态判断
        /// </summary>
        /// <param name="currentManager"></param>
        /// <param name="opt"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private bool CheckManagerStatus(tb_Emp_Manager_Zbdl currentManager, int opt, string areaCode)
        {
            bool flag = true;
            ///如果人员即是管理人员又是从业人员
            if (currentManager.TypeFlag != "-1")
            {
                string[] attrTypeFlag = currentManager.TypeFlag.Split(',');
                foreach (string attr in attrTypeFlag)
                {
                    if (attr == "-1")
                        continue;
                    //判断管理人员职位状态是否存可修改
                    DTO.OperationResult result3 = CheckManagerStatus(currentManager.CorpGuid.ToString(), attr, currentManager.EmpGuid.ToString(), opt, areaCode);
                    if (!result3.Result)
                    {
                        flag = false;
                        break;
                    }
                }
            }
            return flag;
        }
        /// <summary>
        /// 判断管理人员职位是否可修改
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="typeFlag"></param>
        /// <param name="empGuid"></param>
        /// <param name="opt"></param>
        /// <param name="currentAreaCode"></param>
        /// <returns></returns>
        public override OperationResult CheckManagerStatus(string corpUserGuid, string typeFlag, string empGuid, int opt, string currentAreaCode)
        {

            ///方法存在漏洞:当用户把其他地区上报的管理人员作为从业人员添加到当前地区，企业在当前地区未上报时，他就可以修改其他地区上报的管理人员。
            ///当一个管理人员有多个职位并且职位是在不同的地区添加时，它可在其中未上报的地区修改该管理人员的所有职位状态。
            OperationResult result = new OperationResult();
            if (typeFlag == "-1")
            {
                result.Result = true;
                return result;
            }
            try
            {
                ///取得企业当前市场审核状态
                result = CheckCorpStasus(corpUserGuid, currentAreaCode, opt, currentAreaCode);
                if (!result.Result)
                {
                    return result;
                }
                ////取得企业当前职位的审核市场
                Guid corpGuid = Guid.Parse(corpUserGuid);
                var dbEmpFlowAreaCode = zbdlcontext.ManagerInfoFlow.Where(m => m.CorpGuid == corpGuid && m.TypeFlag.Contains(typeFlag) && (m.IsDel == null || m.IsDel == false)).Select(m => m.FlowAreaCode).ToList();
                //当前职位不存在
                if (dbEmpFlowAreaCode == null || dbEmpFlowAreaCode.Count == 0 || dbEmpFlowAreaCode.FirstOrDefault() == null)
                {
                    result.Result = true;
                    return result;
                }
                //职位是否在当前市场有审核记录
                if (dbEmpFlowAreaCode.Contains(currentAreaCode))
                {
                    result.Result = true;
                    return result;
                }
                result.Result = false;
                result.Message = "该职位人员是在其他市场添加，在该市场范围只有查看功能。";
                return result;

                ////管理人员的审核状态获取方式：
                ////若该管理人员的审核地（tb_flowCode中的areacode）包含当前市场，即该管理人员在当前市场添加，则取企业在当前市场的审核状态
                ////若管理人员的审核地（tb_flowCode中的areacode）不包含当前市场，即该管理人员在其他市场添加，则默认在当前市场范围为不可操作状态，认为是审核通过状态
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            return result;
        }
        #endregion

        #region 人员相关图片名称查询,用于保存上报前信息检查

        /// <summary>
        /// 根据不同系统和地区，获取必须上传的图片类型
        /// </summary>
        /// <param name="appId">系统编号</param>
        /// <param name="areaCode">地区编号</param>
        private string GetFileTypes(string appId, string areaCode)
        {
            string psnFileType = string.Empty;

            switch (appId)
            {
                case "95":
                    psnFileType = "Person,PersonID,PersonSign,PersonZC";
                    break;
                default:
                    psnFileType = "Person,PersonID,PersonZC,PersonKH,PersonZG";
                    break;
            }
            return psnFileType;
        }

        /// <summary>
        /// 返回人员相关图片名
        /// </summary>
        public override IList<DTO.PsnFileNames> GetPsnFileNames(IList<string> empGuids, string appId, string areaCode)
        {
            string[] psnFileTypeArray = GetFileTypes(appId, areaCode).Split(',');
            ///返回人员
            Dictionary<Guid, string> dict = GetPsnEmpNameList(empGuids);
            if (dict == null || dict.Count == 0)
            {
                return null;
            }
            List<DTO.PsnFileNames> psnImgs = new List<DTO.PsnFileNames>();
            List<DTO.PsnFileNames> tmpImgs = new List<DTO.PsnFileNames>();
            foreach (string s in psnFileTypeArray)
            {
                switch (s)
                {
                    case "Person":
                        tmpImgs = GetPsnIconNames(dict, "Person", "头像");
                        break;
                    case "PersonID":
                        tmpImgs = GetPsnCardIDNames(dict, "PersonID", "身份证");
                        break;
                    case "PersonZC":
                        tmpImgs = GetPsnPostNames(dict, "PersonZC", "职称证");
                        break;
                    case "PersonKH":
                        tmpImgs = GetPsnCertBNames(dict, "PersonKH", "安全考核证");
                        break;
                    case "PersonZG":
                        tmpImgs = GetPsnCertNames(dict, "PersonZG", "资格证书");
                        break;
                }

                psnImgs = psnImgs.Union(tmpImgs).ToList();
            }
            return psnImgs.OrderBy(p => p.EmpGuid).ToList();
        }
        /// <summary>
        /// 返回人员信息
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        private Dictionary<Guid, string> GetPsnEmpNameList(IList<string> empGuids)
        {
            List<Guid> Guids = new List<Guid>();
            foreach (string e in empGuids)
            {
                Guid eGuid = Guid.Empty;
                if (Guid.TryParse(e, out eGuid))
                {
                    Guids.Add(eGuid);
                }
            }
            ////查询人员
            return zbdlcontext.Emp_Manager.Where(m => (m.IsDel == false || m.IsDel == null) && Guids.Contains(m.EmpGuid)).Distinct().ToDictionary(m => m.EmpGuid, m => m.Name);

        }

        /// <summary>
        /// 取得人员头像图片名称
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        private List<DTO.PsnFileNames> GetPsnIconNames(Dictionary<Guid, string> dict, string fileType, string message)
        {
            List<DTO.PsnFileNames> imgs = new List<DTO.PsnFileNames>();
            foreach (var s in dict)
            {
                imgs.Add(GetPsnFileName(s.Key.ToString(), s.Value, s.Key.ToString(), fileType, message));
            }
            return imgs;
        }
        /// <summary>
        /// 取得人员身份证图片名
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        private List<DTO.PsnFileNames> GetPsnCardIDNames(Dictionary<Guid, string> dict, string fileType, string message)
        {
            List<DTO.PsnFileNames> imgs = new List<DTO.PsnFileNames>();
            foreach (var s in dict)
            {
                imgs.Add(GetPsnFileName(s.Key.ToString(), s.Value, s.Key.ToString(), fileType, message));
            }
            return imgs;
        }
        /// <summary>
        /// 取得人员职称图片名
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        private List<DTO.PsnFileNames> GetPsnPostNames(Dictionary<Guid, string> dict, string fileType, string message)
        {
            List<DTO.PsnFileNames> imgs = new List<DTO.PsnFileNames>();
            foreach (var s in dict)
            {
                int empPosts = zbdlcontext.Emp_Post.Where(q => q.EmpGuid == s.Key && (q.IsDel == false || q.IsDel == null)).Count();
                if (empPosts > 0)
                {
                    imgs.Add(GetPsnFileName(s.Key.ToString(), s.Value, s.Key.ToString(), fileType, message));
                }
            }
            return imgs;

        }
        /// <summary>
        /// 取得人员安全考核证图片名
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        private List<DTO.PsnFileNames> GetPsnCertBNames(Dictionary<Guid, string> dict, string fileType, string message)
        {
            List<DTO.PsnFileNames> imgs = new List<DTO.PsnFileNames>();
            foreach (var s in dict)
            {
                var qualitie = zbdlcontext.Emp_TitleDetailsExt.Where(q => q.EmpGuid == s.Key && (q.IsDel == false || q.IsDel == null)).Select(q => q.EducationGUID).FirstOrDefault();
                if (qualitie != null && qualitie != Guid.Empty)
                {
                    imgs.Add(GetPsnFileName(s.Key.ToString(), s.Value, qualitie.ToString(), fileType, message));
                }

            }
            return imgs;
        }
        /// <summary>
        /// 取得人员资格证书图片名
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        private List<DTO.PsnFileNames> GetPsnCertNames(Dictionary<Guid, string> dict, string fileType, string message)
        {
            string title = string.Empty;
            List<DTO.PsnFileNames> imgs = new List<DTO.PsnFileNames>();
            foreach (var s in dict)
            {
                var qualities = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == s.Key && (q.IsDel == false || q.IsDel == null)).Select(q => new { q.EducationGUID, q.CertificateCode, q.StampCode }).ToList();
                if (qualities != null && qualities.Count > 0)
                {
                    foreach (var qualitie in qualities)
                    {
                        if (qualitie.StampCode == "ZGZS")
                        {
                            imgs.Add(GetPsnFileName(s.Key.ToString(), s.Value, qualitie.EducationGUID.ToString(), fileType, message));
                        }
                    }
                }
            }
            return imgs;
        }

        /// <summary>
        /// 加载结果集实体
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="empName"></param>
        /// <param name="fileName"></param>
        /// <param name="fileType"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        private DTO.PsnFileNames GetPsnFileName(string empGuid, string empName, string fileName, string fileType, string title)
        {
            DTO.PsnFileNames psn = new PsnFileNames();
            psn.EmpGuid = empGuid;
            psn.EmpName = empName;
            psn.FileNames = fileName;
            psn.FileType = fileType;
            psn.Title = title;
            return psn;
        }

        #endregion

        /// <summary>
        /// 人员锁定解锁
        /// </summary>
        /// <param name="empGuids"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult SetPersonIsZZemp(IList<string> empGuids, byte empFlag, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            List<tb_Emp_Manager_Zbdl> emps = new List<tb_Emp_Manager_Zbdl>();
            foreach (var item in empGuids)
            {
                ////判断人员是否存在
                result = CheckEmpIsExist(item);
                if (!result.Result)
                {
                    continue;
                }
                var manager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                emps.Add(manager);
            }
            using (DbConnection con = ((IObjectContextAdapter)zbdlcontext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var item in emps)
                    {
                        tb_Emp_Manager_Zbdl dbEmp = item;
                        dbEmp.isZZEmp = empFlag;
                        zbdlcontext.SaveChanges();
                        result.Message += "对人员" + dbEmp.Name + "的操作执行成功！";
                        ////2.日志
                        var flag = SetUserLog("锁定人员信息", dbEmp, "", "6", areaCode, dbEmp.CorpGuid.ToString());
                        if (!flag)
                        {
                            result.Result = false;
                            result.Message = "日志写入出错！";
                            return result;
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "锁定或解锁人员失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        public override string GetManagerByZbdlDogid(int dogid)
        {
            var qdContext = new DAL.QD_Context();
            var qdEmps = qdContext.Emp_Manager;
            var qdDetails = qdContext.Emp_Qualities;
            var query = from qdEmp in qdEmps
                        join qdDetail in qdDetails on qdEmp.EmpGuid equals qdDetail.EmpGuid
                        into empDetails
                        from empDetail in empDetails.DefaultIfEmpty()
                        where qdEmp.empdogid == dogid
                        select new
                        {
                            Id = qdEmp.ID,
                            CertificateCode = empDetail.CertificateCode,
                            Name = qdEmp.Name,
                            TypeFlag = qdEmp.TypeFlag,
                            CsCode = empDetail.CSCode + empDetail.CertificateName,
                            ClCode = empDetail.CLCode
                        };
            return JsonConvert.SerializeObject(query.FirstOrDefault());
        }

        public override DataTable GetKaoheRst(string bFlag, string queryStr, string querymember, string outer, string zizhi, int pageIndex, int pageSize, out int dataCount)
        {
            return new DAL.LcDAL.PersonDALWh().GetKaoheRst(bFlag, queryStr, querymember, outer, zizhi, pageIndex, pageSize, out dataCount);
        }

        #region 人员添加执业手册
        /// <summary>
        /// 取得上报后的执业手册列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetEmpCertList(string condition,
            int pageNum,
            int pageSize,
            string areaCode)
        {
            List<DTO.QueryChangeInfoCondition> conList = JsonConvert.DeserializeObject<List<DTO.QueryChangeInfoCondition>>(condition);
            var query = from cert in zbdlcontext.EmpCert
                        where cert.CodeType == 251201 && cert.AreaCode == areaCode
                        select new PersonEmpCert()
                        {
                            ID = cert.ID,
                            EducationGUID = cert.EducationGUID,
                            ObjectId = cert.ObjectId,
                            AreaCode = cert.AreaCode,
                            RoleId = cert.RoleId,
                            UserId = cert.UserId,
                            Description = cert.Description,
                            CodeType = cert.CodeType,
                            FlowCode = cert.FlowCode,
                            UpdateTime = cert.UpdateTime,
                            ZsRegisterDate = cert.ZsRegisterDate,
                            ObjectName = cert.Name,
                            IsrtUserName = cert.CorpName,
                            UserGuid = cert.CorpUserGuid,
                            EmpGuid = cert.EmpGuid,
                            EmpId = cert.EmpId
                        };

            if (conList != null && conList.Count > 0)
            {
                query = query.BuildCondition<PersonEmpCert>(conList);
            }
            var result = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            List<PersonEmpCert> list = new List<PersonEmpCert>();
            foreach (var item in result)
            {
                item.StrFlowCode = GetFlowCodeTitle(
                    item.FlowCode,
                    "251201",
                    areaCode);
                list.Add(item);
            }
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        /// 取得上报后的执业手册列表数
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetEmpCertListCount(string condition, string areaCode)
        {
            List<DTO.QueryChangeInfoCondition> conList = JsonConvert.DeserializeObject<List<DTO.QueryChangeInfoCondition>>(condition);
            var query = from cert in zbdlcontext.EmpCert
                        where cert.CodeType == 251201 && cert.AreaCode == areaCode
                        select new PersonEmpCert()
                        {
                            ID = cert.ID,
                            EducationGUID = cert.EducationGUID,
                            ObjectId = cert.ObjectId,
                            AreaCode = cert.AreaCode,
                            RoleId = cert.RoleId,
                            UserId = cert.UserId,
                            Description = cert.Description,
                            CodeType = cert.CodeType,
                            FlowCode = cert.FlowCode,
                            UpdateTime = cert.UpdateTime,
                            ZsRegisterDate = cert.ZsRegisterDate,
                            ObjectName = cert.Name,
                            IsrtUserName = cert.CorpName,
                            UserGuid = cert.CorpUserGuid,
                            EmpGuid = cert.EmpGuid
                        };

            if (conList != null && conList.Count > 0)
            {
                query = query.BuildCondition<PersonEmpCert>(conList);
            }
            var result = query.Count();
            return result;
        }

        /// <summary>
        /// 返回证书审核状态
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="empGuid"></param>
        /// <param name="optType"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetCardFlowCodes(string corpUserGuid, string empGuid, string cardGuid, int codeType, int optType, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            try
            {
                ////判断人员是否存在
                result = CheckEmpIsExist(empGuid);
                if (!result.Result)
                {
                    return result;
                }
                if (string.IsNullOrEmpty(cardGuid))
                {
                    ////取得第一个证书
                    var Qualitie = JsonConvert.DeserializeObject<List<DTO.Tb_Emp_TitleDetails>>(GetEmpQualities(empGuid, areaCode)).Where(q => q.StampCode != "ZGZS").OrderByDescending(q => q.ID).FirstOrDefault();
                    if (Qualitie != null)
                    {
                        cardGuid = Qualitie.EducationGUID.ToString();
                    }
                }
                ///判断证书是否存在
                result = CheckQualityIsExist(cardGuid);
                if (!result.Result)
                {
                    return result;
                }
                ////取得审核状态
                List<DTO.OperationResult> resultList = new List<DTO.OperationResult>();
                string area = string.Empty;
                for (int i = 0; i <= optType; i++)
                {

                    DTO.OperationResult result1 = CheckSubFlowCode(cardGuid, i, codeType, corpUserGuid);
                    resultList.Add(result1);
                }
                result.Result = true;
                result.ReturnValue = resultList;
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "获取审核状态失败" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 取得人员职业手册列表
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override string GetEmpTitleDetails(string empGuid, int codeType, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                return string.Empty;
            }
            var qualities = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == eGuid && (q.IsDel == false || q.IsDel == null)).ToList();
            List<DTO.Tb_Emp_TitleDetails> list_D = new List<DTO.Tb_Emp_TitleDetails>();
            ////实体转换
            string EducationGUID = string.Empty;
            foreach (Tb_Emp_TitleDetails_Zbdl item in qualities)
            {
                DTO.Tb_Emp_TitleDetails item_D = new DTO.Tb_Emp_TitleDetails();
                EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                EducationGUID = item_D.EducationGUID.ToString();
                item_D.StrFlowCode = "";
                ///取得审核状态
                string flowCode = zbdlcontext.FlowCodes.Where(f => f.ObjectId == EducationGUID && f.CodeType == codeType && (f.IsDel == false || f.IsDel == null)).Select(f => f.FlowCode).FirstOrDefault();
                item_D.FlowCode = flowCode;
                if (!string.IsNullOrEmpty(flowCode))
                {
                    item_D.StrFlowCode = GetFlowCodeTitle(flowCode, codeType.ToString(), areaCode);
                }
                list_D.Add(item_D);
            }
            return JsonConvert.SerializeObject(list_D);

        }
        /// <summary>
        /// 取得待打印的证书信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="typeFlag"></param>
        /// <param name="certCode"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetEmpCertInfoPrint(string empGuid, string typeFlag, string certCode, string areaCode)
        {
            DTO.OperationResult result = new OperationResult();
            try
            {
                ////判断人员是否存在
                result = CheckEmpIsExist(empGuid);
                if (!result.Result)
                {
                    return result;
                }
                tb_Emp_Manager_Zbdl emp = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                DTO.tb_Emp_Manager emp_D = new DTO.tb_Emp_Manager();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(emp, emp_D);
                //职称
                var a_posts = zbdlcontext.a_PostPszgDefine;
                var emp_posts = zbdlcontext.Emp_Post;
                var query = from e_post in emp_posts
                            join a_post in a_posts on
                            e_post.Post_psZG equals a_post.Code
                            where e_post.EmpGuid == emp_D.EmpGuid && e_post.IsDel == false
                            select new
                            {
                                Title = a_post.Title
                            };

                emp_D.Post_Title = query.Select(t => t.Title).FirstOrDefault();
                //单位
                emp_D.corpName = zbdlcontext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == emp_D.CorpGuid && c.IsDel == false).Select(c => c.CorpName).FirstOrDefault();
                //证书
                int tFlags = 0;
                int.TryParse(typeFlag, out tFlags);
                var qualities = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == emp_D.EmpGuid && (q.IsDel == false || q.IsDel == null) && q.TypeFlags == tFlags && q.CertificateCode == certCode).ToList();
                if (qualities.Count() == 0)
                {
                    result.Result = false;
                    result.Message = "人员的证书不存在！";
                    return result;
                }
                //多专业
                emp_D.CertificateCode = certCode;
                foreach (Tb_Emp_TitleDetails_Zbdl item in qualities)
                {
                    emp_D.CertificateLevel = item.CLCode;
                    emp_D.CertificateName = item.CertificateName;
                    emp_D.CertificateSpecialty += item.CSCode + ",";
                }
                emp_D.CertificateSpecialty.TrimEnd(',');
                result.Result = true;
                result.ReturnValue = emp_D;
                return result;
            }
            catch
            {
                result.Result = false;
                result.ReturnValue = null;
                return result;
            }
        }

        #endregion

        #region 专家证书补充功能

        #region 从注册中心取用户的执业注册信息导入数据库

        /// <summary>
        /// 从注册中心取用户的执业注册信息导入数据库
        /// </summary>
        /// <param name="idCard"></param>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult ImportEmpTitleDetails(string idCard, string empGuid, string areaCode)
        {
            DTO.OperationResult result = CheckEmpIsExist(empGuid);
            if (!result.Result)
            {
                return result;
            }
            tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
            string content = string.Empty;
            OperationResult ret = InnerImportEmpTitleDetails(idCard.Trim());
            if (ret.Result)
            {
                content = ret.Message;
            }
            else
            {
                result.Message = ret.Message;
                result.Result = false;
            }
            if (!string.IsNullOrEmpty(content) && content.Length > 0)
            {
                result.Result = ConvertAndSaveEmpTitleDetails(content, currentManager, areaCode);
            }
            return result;
        }

        /// <summary>
        /// 从注册中心取用户的执业注册信息。
        /// </summary>
        /// <param name="idCard"></param>
        /// <returns></returns>
        private OperationResult InnerImportEmpTitleDetails(string idCard)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            try
            {
                if (System.Configuration.ConfigurationManager.AppSettings["ImportEmpTitleDetailsUrl"] != null)
                {
                    string importUrl = System.Configuration.ConfigurationManager.AppSettings["ImportEmpTitleDetailsUrl"].ToString();
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(importUrl + idCard);
                    myRequest.Method = "POST";
                    myRequest.ContentType = "application/x-www-form-urlencoded";
                    Stream newStream = myRequest.GetRequestStream();
                    newStream.Close();
                    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                    result.Message = reader.ReadToEnd();
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = "从注册中心获取数据失败" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 保存取得的用户执业注册信息
        /// </summary>
        /// <param name="content"></param>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private bool ConvertAndSaveEmpTitleDetails(string content, tb_Emp_Manager_Zbdl currentManager, string areaCode)
        {
            try
            {
                ////1.取得XML文件中的资格证书。
                List<Tb_Emp_TitleDetails> convertTitles = ParseEmpTitldDetailsXml(content);
                if (convertTitles == null || convertTitles.Count == 0)
                {
                    return false;
                }
                ////2.取得人员已有的资格证书
                List<Tb_Emp_TitleDetails> titles = JsonConvert.DeserializeObject<List<Tb_Emp_TitleDetails>>(GetEmpQualities(currentManager.EmpGuid.ToString(), areaCode));
                ////根据证书编号去重复
                if (titles != null && titles.Count > 0)
                {
                    List<string> certCodes = titles.Where(t => t.StampCode == "ZGZS-Expert").Select(t => t.CertificateCode).ToList();
                    if (certCodes != null && certCodes.Count > 0)
                    {
                        convertTitles = convertTitles.Where(t => !certCodes.Contains(t.CertificateCode)).ToList();
                    }
                }
                if (convertTitles.Count > 0)
                {
                    EmpTitleDetailsAdd(convertTitles, currentManager, areaCode);
                    return true;
                }
            }
            catch { }
            return false;

        }

        /// <summary>
        /// 解析XML返回证书信息
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private List<Tb_Emp_TitleDetails> ParseEmpTitldDetailsXml(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return null;
            }
            ////取得对应配置文件
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(content);
            XmlNode theSys = doc.DocumentElement;
            ////取得配置项
            XmlNodeList sysNodes = theSys.SelectNodes("//ZCRY//certificate");
            if (sysNodes == null)
            {
                return null;
            }
            List<Tb_Emp_TitleDetails> titles = new List<Tb_Emp_TitleDetails>();
            ////取得数据字典
            BasicBLL bll = new BasicBLL();
            var certs = bll.GetQualitiesDic("ZGZS-Expert", "0");////证书字典列表
            var levels = bll.GetQualitiesDic("ZGDJ", "0");////等级字典列表
            var specialtys = bll.GetQualitiesDic("specialty", "0");////专业字典列表
            ////转换数据
            int count = 0;
            foreach (XmlNode sysNode in sysNodes)
            {
                ////定义保存证书信息的变量
                string level = string.Empty;
                string certificateSpecialty = string.Empty;
                string typeFlags = string.Empty;
                string cLCode = string.Empty;
                string specials = string.Empty;
                ////无编号不导入
                string code = sysNode.InnerText.Trim();
                if (code.Trim().Length <= 2)
                {
                    continue;
                }
                string zy = sysNode.Attributes["ZY"].Value.Trim();
                string engineerTypeID = sysNode.Attributes["EngineerTypeID"].Value.Trim();
                if (!string.IsNullOrEmpty(engineerTypeID))
                {
                    engineerTypeID = Regex.Replace(engineerTypeID, "（", "(", RegexOptions.IgnoreCase);
                    engineerTypeID = Regex.Replace(engineerTypeID, "）", ")", RegexOptions.IgnoreCase);
                }
                string corp = sysNode.Attributes["corp"].Value.Trim();
                ////分出等级和类别
                if (engineerTypeID.IndexOf("级") > 0)
                {
                    cLCode = engineerTypeID.Substring(0, engineerTypeID.IndexOf("级") + 1);
                    engineerTypeID = engineerTypeID.Replace(cLCode, "").Trim();
                    level = levels.Where(c => c.Title.Contains(cLCode)).Select(c => c.Code).FirstOrDefault();
                }
                ////判断类别是否存在
                typeFlags = certs.Where(c => c.Title.Contains(engineerTypeID)).Select(c => c.Code).FirstOrDefault();
                if (string.IsNullOrEmpty(typeFlags))
                {
                    continue;
                }
                ////分专业取得证书列表
                foreach (string a in zy.Split('、'))
                {
                    string specialty = a;
                    ////专业不存在
                    count = specialtys.Where(s => s.Title == specialty).Select(s => s.Code).Count();
                    if (count == 0)
                    {
                        specialty = "其他专业";
                    }
                    if (specials.Split(',').Contains(specialty))
                    {
                        continue;
                    }
                    specials += specialty + ",";

                    certificateSpecialty = specialtys.Where(s => s.Title == specialty).Select(s => s.Code).FirstOrDefault();
                    Tb_Emp_TitleDetails td = new Tb_Emp_TitleDetails();
                    td.CertificateCode = code.Trim();
                    td.CertificateName = engineerTypeID.Trim();
                    td.TypeFlags = int.Parse(typeFlags);
                    td.CSCode = specialty.Trim();
                    td.CertificateSpecialty = int.Parse(certificateSpecialty);
                    td.CLCode = cLCode;
                    td.CertificateLevel = level;
                    td.RegisterCorpName = corp;
                    titles.Add(td);
                }
            }
            return titles;
        }

        /// <summary>
        /// 导入资格证书
        /// </summary>
        /// <param name="empQualities"></param>
        /// <param name="empGuid"></param>
        private void EmpTitleDetailsAdd(List<Tb_Emp_TitleDetails> empQualities, tb_Emp_Manager_Zbdl currentManager, string areaCode)
        {
            foreach (DTO.Tb_Emp_TitleDetails empQualitie in empQualities)
            {
                //添加证书
                Tb_Emp_TitleDetails_Zbdl empQuality_E = new Tb_Emp_TitleDetails_Zbdl();
                EntityHelper.ConvertEntity2OtherEntity(empQualitie, empQuality_E);
                empQuality_E.EmpGuid = currentManager.EmpGuid;
                if (empQuality_E.EducationGUID == Guid.Empty)
                {
                    empQuality_E.EducationGUID = Guid.NewGuid();
                }
                empQuality_E.IsDel = false;
                empQuality_E.FlowCode = "0";
                empQuality_E.StampCode = "ZGZS-Expert";
                empQuality_E.ZsRegisterDate = DateTime.Now.ToString();
                empQuality_E.IsValid = 100;////标识信息是导入的
                empQuality_E = zbdlcontext.Emp_Qualities.Add(empQuality_E);
                zbdlcontext.SaveChanges();
                ZhuanjiaLihaiDwAdd(empQuality_E.EmpGuid.ToString(), empQuality_E.RegisterCorpName, "注册单位", areaCode);
            }
            ////日志
            SetUserLog("导入人员资格证书", currentManager, "07", "1", areaCode, currentManager.CorpGuid.ToString());
        }

        /// <summary>
        /// 添加专家利害单位
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="entityName"></param>
        /// <param name="areaCode"></param>
        private void ZhuanjiaLihaiDwAdd(string empGuid, string entityName, string Reason, string areaCode)
        {
            try
            {
                DTO.tb_User_Relation model = new DTO.tb_User_Relation();
                model.Gid = Guid.NewGuid();
                model.ID = 0;
                model.UserGuid = Guid.Parse(empGuid);////empguid
                model.CreateTime = DateTime.Now;
                model.EntityFlag = 1;
                model.EntityGuid = Guid.NewGuid();
                model.EntityName = entityName;////企业名称
                model.AreaCode = areaCode;
                model.AppId = 95;
                model.Reason = Reason;
                model.ClassId = 1002;
                var result = SaveUserRelationInfo(model);
            }
            catch { }
        }
        #endregion

        /// <summary>
        /// 导入证书修正
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="eduGUIDs"></param>
        /// <param name="remark"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpTitleDetailsEditRemark(string empGuid, string eduGUIDs, string remark, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                ////判断人员状态
                result = CheckEmpStasus(empGuid, string.Empty, 4, areaCode);
                if (!result.Result)
                {
                    return result;
                }
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                Guid eduguid = Guid.Empty;
                string[] educationGUID = eduGUIDs.Split(',');
                foreach (string eduGuid in educationGUID)
                {
                    Guid.TryParse(eduGuid, out eduguid);
                    Tb_Emp_TitleDetails_Zbdl dbEmpQuality = zbdlcontext.Emp_Qualities.Where(p => p.EducationGUID == eduguid && (p.IsDel == false || p.IsDel == null)).FirstOrDefault();
                    ////逻辑删除
                    if (dbEmpQuality == null)
                    {
                        continue;
                    }
                    if (dbEmpQuality.IsValid == null || dbEmpQuality.IsValid != 100)
                    {
                        result.Message += "证书 [" + dbEmpQuality.CertificateName + "]" + "不是系统导入证书，不能编辑！";
                        continue;
                    }

                    dbEmpQuality.Remark = remark;
                    zbdlcontext.SaveChanges();
                    result.Message += "证书 [" + dbEmpQuality.CertificateName + "] 修正操作成功！";
                    result.Result = true;
                    ////2.日志
                    var flag = SetUserLog("导入证书修正", currentManager, "08", "3", areaCode, currentManager.CorpGuid.ToString());
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message = "日志写入出错！";
                        return result;
                    }

                }
                if (string.IsNullOrEmpty(result.Message))
                {
                    result.Result = false;
                    result.Message = "证书不存在！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "证书修正失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }

        #region 专家统计

        public override List<DTO.T_Sys_Dict> GetExpertSpecList()
        {
            ////专家专业codes
            return new BasicBLL().GetSysDicts("ExpSpec", string.Empty).Where(p => p.Code.Length <= 3).ToList();

        }
        /// <summary>
        /// 综合统计
        /// </summary>
        /// <param name="flowCode"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override StatisticsStruct GetPersonExpertStatistic3(string currentCode, string areaCode)
        {
            ////取得全部数据源
            List<StatisticsMode3> source = new PersonDALWh().GetPersonExpertStatistic(currentCode);
            ////专家专业codes
            var expSpecList = GetExpertSpecList();
            List<string> codes = new List<string>();
            if (expSpecList != null && expSpecList.Count > 0)
            {
                codes = expSpecList.Where(p => p.Code.Length == 3).Select(p => p.Code).ToList();
            }
            ////取得专家专业
            Dictionary<string, string> expertDBs = GetExpertDBList(currentCode);
            StatisticsStruct list = new StatisticsStruct();
            ////1、取得标题
            StatisticsStruct.StatisticsHeader header = new StatisticsStruct.StatisticsHeader();
            StatisticsStruct.StatisticsCell hcell1 = new StatisticsStruct.StatisticsCell { Value = "DBType" };
            StatisticsStruct.StatisticsCell hcell2 = new StatisticsStruct.StatisticsCell { Value = "分库" };
            List<StatisticsStruct.StatisticsCell> hcell_list = new List<StatisticsStruct.StatisticsCell>();
            hcell_list.Add(hcell1);
            hcell_list.Add(hcell2);
            foreach (var cl in codes)
            {
                StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                cell.Value = cl;
                hcell_list.Add(cell);
            }
            header.HeaderCells = hcell_list.ToArray();
            List<StatisticsStruct.StatisticsHeader> header_list = new List<StatisticsStruct.StatisticsHeader> { header };
            list.Header = header_list.ToArray();
            ////2、取得行
            List<StatisticsStruct.StatisticsRow> row_list = new List<StatisticsStruct.StatisticsRow>();
            foreach (var expertDB in expertDBs)
            {
                StatisticsStruct.StatisticsRow row = GetPersonExpertStatisticsRow(source, codes, expertDB.Key, expertDB.Value, expertDB.Key);
                row_list.Add(row);
            }
            //3、汇总
            StatisticsStruct.StatisticsRow row3 = GetPersonExpertStatisticsRow(source, codes, currentCode, "合计", string.Empty);
            row_list.Add(row3);
            list.Data = row_list.ToArray();
            return list;
        }
        /// <summary>
        /// 取得每行数据
        /// </summary>
        /// <param name="source"></param>
        /// <param name="classIdList"></param>
        /// <param name="sortCode"></param>
        /// <param name="title"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private StatisticsStruct.StatisticsRow GetPersonExpertStatisticsRow(List<StatisticsMode3> source,
           List<string> classIdList, string sortCode, string title, string areaCode)
        {
            int empCount = 0;
            StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
            List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
            StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = sortCode };
            StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = title };
            cell_list.Add(cell1);
            cell_list.Add(cell2);
            foreach (var cl in classIdList)
            {
                StatisticsStruct.StatisticsCell cell = new StatisticsStruct.StatisticsCell();
                var query = source.Where(s => s.SpecialityCode == cl);
                if (!string.IsNullOrEmpty(areaCode))
                {
                    //取得子地区数目
                    empCount = query.Where(s => s.DBType.StartsWith(areaCode)).Sum(s => s.StatisticsCount);
                }
                else
                {
                    //取得统计数
                    empCount = query.Sum(s => s.StatisticsCount);
                }
                cell.Value = empCount.ToString();
                cell_list.Add(cell);
            }
            row.DataCells = cell_list.ToArray();
            return row;
        }


        /// <summary>
        /// 取得专家库别
        /// </summary>
        /// <param name="currentCode"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetExpertDBList(string currentCode)
        {

            ////取得专家库别
            Dictionary<string, string> expertDBs = new Dictionary<string, string>();
            List<DTO.T_Sys_Dict> expertDBList = new BasicBLL().GetExpertDBList();

            if (currentCode != null && currentCode != "00" && currentCode.Length >= 2)
            {
                ////取得子库信息
                expertDBs = expertDBList.Where(e => e.Code.StartsWith(currentCode) && e.ParentSID > 0)
                    .ToDictionary(e => e.Code, e => e.Name);
            }
            else
            {
                expertDBs = expertDBList.Where(e => e.ParentSID == 0)
                    .ToDictionary(e => e.Code, e => e.Name);
            }
            return expertDBs;
        }
        /// <summary>
        /// 考试报名统计
        /// </summary>
        /// <param name="qcId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override StatisticsStruct GetExpertBMStatistic(int qcId, string currentCode, string areaCode)
        {
            ////取得全部数据源
            List<StatisticsMode4> source = new PersonDALWh().GetExpertBMStatistic(qcId, currentCode);

            ////取得专家库别
            Dictionary<string, string> expertDBs = GetExpertDBList(currentCode);
            StatisticsStruct list = new StatisticsStruct();
            ////1、取得标题
            StatisticsStruct.StatisticsHeader header = new StatisticsStruct.StatisticsHeader();
            StatisticsStruct.StatisticsCell hcell1 = new StatisticsStruct.StatisticsCell { Value = "DBType" };
            StatisticsStruct.StatisticsCell hcell2 = new StatisticsStruct.StatisticsCell { Value = "地区" };
            StatisticsStruct.StatisticsCell hcell3 = new StatisticsStruct.StatisticsCell { Value = "应报名人数" };
            StatisticsStruct.StatisticsCell hcell4 = new StatisticsStruct.StatisticsCell { Value = "已报名缴费人数" };
            StatisticsStruct.StatisticsCell hcell5 = new StatisticsStruct.StatisticsCell { Value = "未报名缴费人数" };
            List<StatisticsStruct.StatisticsCell> hcell_list = new List<StatisticsStruct.StatisticsCell>();
            hcell_list.Add(hcell1);
            hcell_list.Add(hcell2);
            hcell_list.Add(hcell3);
            hcell_list.Add(hcell4);
            hcell_list.Add(hcell5);
            header.HeaderCells = hcell_list.ToArray();
            List<StatisticsStruct.StatisticsHeader> header_list = new List<StatisticsStruct.StatisticsHeader> { header };
            list.Header = header_list.ToArray();
            ////2、取得行
            List<StatisticsStruct.StatisticsRow> row_list = new List<StatisticsStruct.StatisticsRow>();
            foreach (var expertDB in expertDBs)
            {
                StatisticsStruct.StatisticsRow row = GetExpertBMStatisticsRow(source, expertDB.Key, expertDB.Value, expertDB.Key);
                row_list.Add(row);
            }
            //3、汇总
            StatisticsStruct.StatisticsRow row3 = GetExpertBMStatisticsRow(source, currentCode, "合计", currentCode);
            row_list.Add(row3);
            list.Data = row_list.ToArray();
            return list;
        }
        /// <summary>
        /// 取得单行记录
        /// </summary>
        /// <param name="source"></param>
        /// <param name="DBType"></param>
        /// <param name="title"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private StatisticsStruct.StatisticsRow GetExpertBMStatisticsRow(List<StatisticsMode4> source, string DBType, string title, string areaCode)
        {
            int empCount = 0;
            int examCount = 0;
            int otherCount = 0;
            ////定义单元格
            StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
            List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
            StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = DBType };
            StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = title };
            cell_list.Add(cell1);
            cell_list.Add(cell2);
            StatisticsStruct.StatisticsCell cell3 = new StatisticsStruct.StatisticsCell();
            StatisticsStruct.StatisticsCell cell4 = new StatisticsStruct.StatisticsCell();
            StatisticsStruct.StatisticsCell cell5 = new StatisticsStruct.StatisticsCell();
            if (!string.IsNullOrEmpty(areaCode) && areaCode != "00")
            {
                ////取得子地区应报名和已报名人数
                empCount = source.Where(s => s.DBType.StartsWith(areaCode)).Sum(s => s.StatisticsCount);
                examCount = source.Where(s => s.DBType.StartsWith(areaCode)).Sum(s => s.StatisticsCount1);
            }
            else
            {
                //取得统计数
                empCount = source.Sum(s => s.StatisticsCount);
                examCount = source.Sum(s => s.StatisticsCount1);
            }
            ////取得未报名人数
            otherCount = empCount - examCount;
            cell3.Value = empCount.ToString();
            cell4.Value = examCount.ToString();
            cell5.Value = otherCount.ToString();
            cell_list.Add(cell3);
            cell_list.Add(cell4);
            cell_list.Add(cell5);
            row.DataCells = cell_list.ToArray();
            return row;
        }


        #endregion

        #endregion

        /// <summary>
        /// 获取人员考核分数
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="Bgrade"></param>
        /// <param name="bFlag"></param>
        /// <returns></returns>
        public override List<e_SorcePublish_2006> GetPsnAssessInfo(string empGuid, int bgrade, int bFlag)
        {
            List<e_SorcePublish_2006_Zbdl> e_score = new List<e_SorcePublish_2006_Zbdl>();
            Guid guid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out guid))
            {
                return null;
            }
            var emp = zbdlcontext.Emp_Manager.Where(c => c.EmpGuid == guid).FirstOrDefault();
            if (emp != null)
            {
                e_score = zbdlcontext.SorcePublish.Where(e => e.bGrade == bgrade && e.bFlag == bFlag && e.KindID == emp.ID).ToList();
            }
            var dtolist = new List<DTO.e_SorcePublish_2006>();
            foreach (var item in e_score)
            {
                DTO.e_SorcePublish_2006 score_D = new DTO.e_SorcePublish_2006();
                ////用Entity为入参DTO赋值
                EntityHelper.ConvertEntity2OtherEntity(item, score_D);
                dtolist.Add(score_D);
            }
            return dtolist;
        }

        /// <summary>
        /// 取得外网人员列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetPortalEmpList(int pageCount, int pageSize, string conditions, string areaCode)
        {
            ////1.查询满足条件的用户guid。
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            ////监理企业监理工程师的考核分
            var dbScore = zbdlcontext.SorcePublish.Where(o => o.bGrade == 42 && o.bFlag == 22);
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on emps.EmpGuid equals post.EmpGuid into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on emps.EmpGuid equals title.EmpGuid into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        join score in dbScore on emps.ID equals score.KindID into jScores
                        from scores in jScores.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (posts.IsDel == null || posts.IsDel == false) && (emps.IsDel == null || emps.IsDel == false)
                        && (titles.IsDel == false || titles.IsDel == null) && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体

                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            Post_Corp = posts.Post_Corp,
                            Post_Major = posts.Post_Major,
                            Post_psDate = posts.Post_psDate,
                            Post_psOrg = posts.Post_psOrg,
                            Post_psZG = posts.Post_psZG,
                            Post_psZGCode = posts.Post_psZGCode,
                            PostId = posts.Id,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            Year_Sorce = scores.Year_Sorce
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }

            var empGuids = new List<Guid>();
            if (pageSize > 0)
            {
                empGuids = query.OrderByDescending(q => q.Year_Sorce).ThenByDescending(o => o.ID)
                    .Select(q => q.EmpGuid).ToList().Distinct()
                    .Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                empGuids = query.Select(q => q.EmpGuid).ToList().Distinct().ToList();
            }

            ////2.查询人员信息。
            var query1 = from emps in dbEmp
                         join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                         join post in dbEmpPost on emps.EmpGuid equals post.EmpGuid into jPosts
                         from posts in jPosts.DefaultIfEmpty()
                         join title in dbTitles on emps.EmpGuid equals title.EmpGuid into jTitles
                         from titles in jTitles.DefaultIfEmpty()
                         join score in dbScore on emps.ID equals score.KindID into jScores
                         from scores in jScores.DefaultIfEmpty()
                         where emps.FlowAreaCode == areaCode && empGuids.Contains(emps.EmpGuid) && (posts.IsDel == null || posts.IsDel == false) && (emps.IsDel == null || emps.IsDel == false)
                        && (titles.IsDel == false || titles.IsDel == null) && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                         select new tb_Emp_Manager()
                         {
                             #region 封装实体

                             EmpGuid = emps.EmpGuid,
                             AreaCode = emps.AreaCode,
                             FlowCode = emps.RealFlowCode,
                             corpName = companies.CorpName,
                             Birthday = emps.Birthday,
                             BithdayMonth = emps.BithdayMonth,
                             BithdayYear = emps.BithdayYear,
                             ClassId = emps.ClassId,
                             CorpClassID = emps.CorpClassID,
                             CorpGuid = emps.CorpGuid,
                             CorpID = emps.CorpID,
                             CreatDate = emps.CreatDate,
                             DogID = emps.DogID,
                             DoMajor = emps.DoMajor,
                             Duty = emps.Duty,
                             DutyLevel = emps.Duty,
                             Education = emps.Education,
                             EMail = emps.EMail,
                             empdogid = emps.empdogid,
                             EmployeeType = emps.EmployeeType,
                             GraduatedSchool = emps.GraduatedSchool,
                             ID = emps.ID,
                             IDCard = emps.IDCard,
                             IDType = emps.IDType,
                             InsuranceNum = emps.InsuranceNum,
                             //InsutanceCode=emps.
                             isFreeze = emps.isFreeze,
                             IsLeave = emps.IsLeave,
                             MobileTel = emps.MobileTel,
                             Name = emps.Name,
                             OrginazationCode = companies.OrginazationCode,
                             Post_Corp = posts.Post_Corp,
                             Post_Major = posts.Post_Major,
                             Post_psDate = posts.Post_psDate,
                             Post_psOrg = posts.Post_psOrg,
                             Post_psZG = posts.Post_psZG,
                             Post_psZGCode = posts.Post_psZGCode,
                             PostId = posts.Id,
                             pwd = emps.pwd,
                             Sex = emps.Sex,
                             SpecialityID = emps.SpecialityID,
                             Tel = emps.Tel,
                             TypeFlag = emps.TypeFlag,
                             ZhiWu = emps.ZhiWu,
                             TypeFlags = titles.TypeFlags,
                             CertificateCode = titles.CertificateCode,
                             CertificateLevel = titles.CertificateLevel,
                             CertificateName = titles.CertificateName,
                             CertificateSpecialty = titles.CertificateSpecialty,
                             Year_Sorce = scores.Year_Sorce
                             #endregion
                         };
            var result = query1.OrderByDescending(o => o.TypeFlags != null && o.TypeFlags == 4202)
                               .ThenByDescending(o => o.TypeFlags != null && o.TypeFlags == 4203)
                               .ThenByDescending(o => o.TypeFlags != null && o.TypeFlags == 4201)
                               .ThenByDescending(o => o.TypeFlags != null && o.TypeFlags == 4204)
                               .ToList();

            ////3.封装数据。
            ////取得职称名
            Dictionary<string, string> data = (from dic in zbdlcontext.a_PostPszgDefine
                                               select new { dic.Code, dic.Title }).ToDictionary(p => p.Code, p => p.Title);
            var managers = new List<tb_Emp_Manager>();
            ////如果实体需要翻译，在此循环遍历翻译。
            string strTitleDetails = string.Empty;
            string titleCode = string.Empty;
            string strTitlePost = string.Empty;
            foreach (var manager in result)
            {
                var mgr = managers.SingleOrDefault(m => m.EmpGuid == manager.EmpGuid);
                if (mgr != null)
                {
                    if (!string.IsNullOrEmpty(mgr.CertificateCode))
                    {
                        if (manager.TypeFlags != null && new string[] { "4202", "4203", "4201", "4204" }.Contains(manager.TypeFlags.ToString()))
                        {
                            if (!titleCode.Split(',').Contains(manager.CertificateCode))
                            {
                                titleCode += "," + manager.CertificateCode;
                                strTitlePost = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                                mgr.Post_Title += "<br/>" + strTitlePost;
                            }
                        }
                        else
                        {
                            titleCode += "," + manager.CertificateCode;
                            strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                            mgr.StrTitleDetails += "<br/>" + strTitleDetails;
                        }
                    }
                }
                else
                {

                    if (!string.IsNullOrEmpty(manager.FlowCode))
                    {
                        manager.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                            areaCode,
                            manager.ClassId.ToString(),
                            manager.FlowCode);
                    }
                    //if (m.Post_psZG != null && data.ContainsKey(m.Post_psZG))
                    //{
                    //    m.Post_Title += data[m.Post_psZG];
                    //}
                    //if (m.Post_psZGCode != null && data.ContainsKey(m.Post_psZGCode))
                    //{
                    //    m.Post_Title += data[m.Post_psZGCode];
                    //}
                    if (!string.IsNullOrEmpty(manager.CertificateCode))
                    {
                        if (manager.TypeFlags != null && new string[] { "4202", "4203", "4201", "4204" }.Contains(manager.TypeFlags.ToString()))
                        {
                            if (!titleCode.Split(',').Contains(manager.CertificateCode))
                            {
                                titleCode += "," + manager.CertificateCode;
                                strTitlePost = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                                manager.Post_Title += "<br/>" + strTitlePost;
                            }
                        }
                        else
                        {
                            titleCode += "," + manager.CertificateCode;
                            strTitleDetails = string.Format("{0}:{1}", manager.CertificateName, manager.CertificateCode);
                            manager.StrTitleDetails += "<br/>" + strTitleDetails;
                        }
                    }
                    managers.Add(manager);
                }
            }
            return managers;
        }

        /// <summary>
        /// 返回人员列表数目
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetPortalEmpListCount(string conditions, string areaCode)
        {
            //////调用DAL中的方法
            //var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
            //var query = zbdlcontext.Emp_Manager.Where(p => (p.IsDel == false || p.IsDel == null));
            //var empsCount = query.BuildCondition<tb_Emp_Manager_Zbdl>(condition).Count();

            //return empsCount;

            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitleDetail = zbdlcontext.Emp_Qualities;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var dbScore = zbdlcontext.SorcePublish.Where(o => o.bGrade == 42 && o.bFlag == 22);
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on emps.EmpGuid equals post.EmpGuid into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on emps.EmpGuid equals title.EmpGuid into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        join score in dbScore on emps.ID equals score.KindID into jScores
                        from scores in jScores.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (posts.IsDel == null || posts.IsDel == false) && (emps.IsDel == null || emps.IsDel == false)
                        && (titles.IsDel == false || titles.IsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体

                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            //InsutanceCode=emps.
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            Post_Corp = posts.Post_Corp,
                            Post_Major = posts.Post_Major,
                            Post_psDate = posts.Post_psDate,
                            Post_psOrg = posts.Post_psOrg,
                            Post_psZG = posts.Post_psZG,
                            Post_psZGCode = posts.Post_psZGCode,
                            PostId = posts.Id,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            TypeFlags = titles.TypeFlags,
                            CertificateCode = titles.CertificateCode,
                            CertificateLevel = titles.CertificateLevel,
                            CertificateName = titles.CertificateName,
                            CertificateSpecialty = titles.CertificateSpecialty,
                            Year_Sorce = scores.Year_Sorce
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            List<int> ret = query.Select(q => q.ID).ToList();
            return ret.Distinct().Count();
        }

        public override void YtdlAdd(string empGuid)
        {
            Guid gEmpGuid = Guid.Empty;
            Guid.TryParse(empGuid, out gEmpGuid);
            var query = from emp in zbdlcontext.Emp_Manager
                        where emp.EmpGuid == gEmpGuid && emp.IfHaveCA == 0
                        select emp;
            tb_Emp_Manager_Zbdl manager = query.FirstOrDefault();
            if (manager != null)
            {
                manager.IfHaveCA = 1;
                zbdlcontext.SaveChanges();
            }
        }

        #endregion

        #region 考试

        /// <summary>
        /// 主管分配考试
        /// </summary>
        /// <param name="groupCode"></param>
        /// <returns></returns>
        public override bool Exam(string groupCode, string groupAddress)
        {
            var query = from exam in zbdlcontext.Exam
                        where exam.IsDel == false && exam.Status == 0
                        select exam;
            var result = query.ToList();
            foreach (var item in result)
            {
                item.Status = 1;
                item.GroupCode = groupCode;
                item.GroupAddress = groupAddress;
            }
            zbdlcontext.SaveChanges();
            return true;
        }

        /// <summary>
        /// 企业报名
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override bool ReportExam(string empGuid, string corpUserGuid)
        {
            Guid empguid = Guid.Parse(empGuid);
            var query = from exam in zbdlcontext.Exam
                        where exam.IsDel == false && exam.EmpGuid == empguid && (exam.Status == 0 || exam.Status == 1)
                        select exam;
            if (query.Count() > 0)
            {
                return false;
            }
            else
            {
                RN.ERP.Entity.ZBDLRY.Tb_Emp_ExamInfo examinfo = new RN.ERP.Entity.ZBDLRY.Tb_Emp_ExamInfo();
                examinfo.CorpUserGuid = Guid.Parse(corpUserGuid);
                examinfo.EmpGuid = empguid;
                examinfo.Status = 0;
                examinfo.IsrtDate = DateTime.Now;
                examinfo.IsDel = false;
                examinfo.ClassId = "251202";
                zbdlcontext.Exam.Add(examinfo);
                zbdlcontext.SaveChanges();
                return true;
            }
        }

        /// <summary>
        /// 获取考试报名列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetReportExamList(int pageCount, int pageSize, string conditions, string areaCode)
        {
            var query = GetetReportExam(conditions, areaCode);
            var result = query.OrderByDescending(o => o.ID).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            return JsonConvert.SerializeObject(result);
        }

        public override int GetReportExamListCount(string conditions, string areaCode)
        {
            var query = GetetReportExam(conditions, areaCode);
            return query.Count();
        }

        private IQueryable<Emp_ExamInfo> GetetReportExam(string conditions, string areaCode)
        {
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var dbExam = zbdlcontext.Exam;
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join exam in dbExam on emps.EmpGuid equals exam.EmpGuid into empexam
                        from exams in empexam.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false) && (exams.IsDel == null || exams.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new Emp_ExamInfo()
                        {
                            CorpUserGuid = companies.CorpUserGuid,
                            CorpName = companies.CorpName,
                            ID = emps.ID,
                            EmpGuid = emps.EmpGuid,
                            TypeFlag = emps.TypeFlag,
                            Name = emps.Name,
                            Sex = emps.Sex,
                            IDCard = emps.IDCard,
                            Tel = emps.Tel,
                            FlowCode = emps.RealFlowCode,
                            AreaCode = emps.FlowAreaCode,
                            Status = exams.Status,
                            IsrtDate = exams.IsrtDate,
                            ClassId = exams.ClassId,
                            EmpStatus = exams.EmpStatus,
                            GroupCode = exams.GroupCode,
                            //Score = exams.Score,
                            ScoreState = exams.ScoreState,
                            GroupAddress = exams.GroupAddress
                        };
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<List<QueryExamInfoCondition>>(conditions);
                query = query.BuildCondition<Emp_ExamInfo>(condition);
            }
            return query;
        }

        #endregion

        #region 专家注册
        public override DTO.OperationResult ExpertReg(DTO.T_Sys_Users user, DTO.Tb_Corp_CompanyInfo corp, DTO.tb_Emp_Manager expert)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.ReturnValue = 0;
            result.Result = false;
            result.Message = "注册失败";
            bool createCorp = true;
            var dbcorp = zbdlcontext.Corp_CompanyInfos.Where(o => o.OrginazationCode == corp.OrginazationCode).FirstOrDefault();
            if (dbcorp != null)
            {
                createCorp = false;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////添加用户信息
                    Entity.ZBDLRY.T_Sys_Users_Zbdl userInfo = new T_Sys_Users_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(user, userInfo);
                    userInfo.AreaCodeScope = userInfo.AreaCode;
                    Guid gid = Guid.NewGuid();
                    userInfo.UserGuid = gid;
                    zbdlcontext.T_Sys_Users.Add(userInfo);

                    ////添加企业信息
                    Entity.ZBDLRY.Tb_Corp_CompanyInfo_Zbdl corpInfo = new Tb_Corp_CompanyInfo_Zbdl();
                    if (createCorp)
                    {
                        EntityHelper.ConvertEntity2OtherEntity(corp, corpInfo);
                        corpInfo.CorpGuid = Guid.NewGuid();
                        corpInfo.CorpUserGuid = gid;
                        corpInfo.FlowCode = "0";
                        if (corpInfo.IsDel == null)
                        {
                            corpInfo.IsDel = false;
                        }
                        zbdlcontext.Corp_CompanyInfos.Add(corpInfo);
                        zbdlcontext.SaveChanges();
                    }

                    ////添加专家信息
                    Entity.ZBDLRY.tb_Emp_Manager_Zbdl expertInfo = new tb_Emp_Manager_Zbdl();
                    EntityHelper.ConvertEntity2OtherEntity(expert, expertInfo);
                    expertInfo.EmpGuid = userInfo.UserGuid;
                    if (createCorp)
                    {
                        expertInfo.CorpGuid = corpInfo.CorpUserGuid;
                        expertInfo.CorpClassID = corpInfo.classID;
                        expertInfo.CorpID = corpInfo.ID.ToString();
                    }
                    else
                    {
                        expertInfo.CorpGuid = dbcorp.CorpUserGuid;
                        expertInfo.CorpClassID = dbcorp.classID;
                        expertInfo.CorpID = corpInfo.ID.ToString();
                    }
                    zbdlcontext.Emp_Manager.Add(expertInfo);
                    zbdlcontext.SaveChanges();

                    ////添加用户角色。
                    string sRoleId = userInfo.RoleID.ToString();
                    Entity.Authority.T_Sys_Roles role = zbdlcontext.SysRoles.FirstOrDefault(r => r.Code == sRoleId && r.IsDel == false);
                    if (role != null)
                    {
                        zbdlcontext.SysUserRoles.Add(new Entity.Authority.T_Sys_UserRole()
                        {
                            IsDel = false,
                            IsrtDate = DateTime.Now,
                            IsrtUseID = userInfo.UserGuid,
                            RoleGuid = role.RoleGuid,
                            UserGuid = userInfo.UserGuid
                        });
                    }

                    ////添加审核记录
                    Entity.ZBDLRY.Tb_FlowCode_Zbdl model = new Entity.ZBDLRY.Tb_FlowCode_Zbdl
                    {
                        AreaCode = userInfo.AreaCode.Substring(0, 2),
                        CodeType = expertInfo.ClassId,
                        FlowCode = "0",
                        IsDel = false,
                        ObjectId = expertInfo.EmpGuid.ToString(),
                        UpdateTime = DateTime.Now
                    };
                    loghelper.AddFlowcode(model);

                    ////注册单位添加为回避单位
                    tb_User_Relation_Zbdlry relationEntity = new tb_User_Relation_Zbdlry();
                    relationEntity.AppId = 95;
                    relationEntity.ClassId = 1003;
                    relationEntity.Gid = Guid.NewGuid();
                    relationEntity.UserGuid = expertInfo.EmpGuid;
                    relationEntity.CreateTime = DateTime.Now;
                    relationEntity.EntityFlag = 1;
                    relationEntity.EntityGuid = corpInfo.CorpUserGuid;
                    relationEntity.EntityName = corpInfo.CorpName;
                    relationEntity.Reason = "现工作单位";
                    relationEntity.AreaCode = "00";
                    relationEntity.IsDel = false;
                    relationEntity.UpdateTime = DateTime.Now;
                    zbdlcontext.UserRelation.Add(relationEntity);
                    zbdlcontext.SaveChanges();

                    ////添加日志
                    loghelper.InsertUserLog("专家注册", corpInfo.ID.ToString(), corpInfo.classID.ToString(), "1");
                    zbdlcontext.SaveChanges();
                    tran.Commit();
                    result.Message = "注册成功。";
                    result.Result = true;
                    result.ReturnValue = 1;

                    ////省注册中心导入证书
                    OperationResult retImport = ImportEmpTitleDetails(expertInfo.IDCard, expertInfo.EmpGuid.ToString(), string.Empty);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "添加失败：" + ex.InnerException; ;
                    result.Result = false;
                    result.ReturnValue = -1;
                }
            }
            return result;

        }
        #endregion

        #region 专家专业与关系
        public override IList<DTO.tb_Expert_Speciality> GetExpertSpecialityList(string empGuid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                return null;
            }
            var query = from specs in zbdlcontext.ExpSpeciality
                        where specs.EmpGuid == eGuid && (specs.IsDel == false || specs.IsDel == null)
                        select new tb_Expert_Speciality()
                        {
                            ID = specs.ID,
                            SpecialityGuid = specs.SpecialityGuid,
                            EmpGuid = specs.EmpGuid,
                            ClassId = specs.ClassId,
                            TypeFlags = specs.TypeFlags,
                            SpecialityName = specs.SpecialityName,
                            SpecialityCode = specs.SpecialityCode,
                            SpecialityLevel = specs.SpecialityLevel,
                            FlowCode = specs.FlowCode,
                            IsMain = specs.IsMain,
                            GetDate = specs.GetDate,
                            UpdateDate = specs.UpdateDate,
                            Remark = specs.Remark
                        };
            query = query.OrderByDescending(o => o.UpdateDate);
            var ret = query.ToList();
            int count = ret.Count();
            var top = ret.Take(20).ToList();
            {
                foreach (var item in top)
                {
                    int sid = int.Parse(item.TypeFlags.ToString());
                    item.SpecialityName = GetSpecialityTitle(sid);
                }
            }
            return ret;
        }

        public override OperationResult ExpertMainSpecCheck(string empGuid, string areaCode)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            ret.ReturnValue = 0;
            ret.Message = "主专业不存在,请添加主专业";
            Guid guid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out guid))
            {
                ret.Message = "参数错误";
                return ret;
            }
            var mainSpec = zbdlcontext.ExpSpeciality.Where(o => o.EmpGuid == guid
            && (o.IsDel == false || o.IsDel == null) && o.IsMain != null && o.IsMain == true).FirstOrDefault();
            if (mainSpec != null)
            {
                ret.Result = true;
                ret.ReturnValue = 1;
                ret.Message = string.Empty;
            }
            return ret;
        }

        public override DTO.tb_Expert_Speciality GetExpertSpeciality(string specialityGuid)
        {
            DbSet<tb_Expert_Speciality_Zbdl> dbSpecs = zbdlcontext.ExpSpeciality;
            Guid sGuid = Guid.Empty;
            if (!Guid.TryParse(specialityGuid, out sGuid))
            {
                return null;
            }
            var query = from spec in dbSpecs
                        where spec.SpecialityGuid == sGuid && (spec.IsDel == false || spec.IsDel == null)
                        select new tb_Expert_Speciality()
                        {
                            ID = spec.ID,
                            SpecialityGuid = spec.SpecialityGuid,
                            EmpGuid = spec.EmpGuid,
                            ClassId = spec.ClassId,
                            TypeFlags = spec.TypeFlags,
                            SpecialityName = spec.SpecialityName,
                            SpecialityCode = spec.SpecialityCode,
                            SpecialityLevel = spec.SpecialityLevel,
                            FlowCode = spec.FlowCode,
                            IsMain = spec.IsMain,
                            GetDate = spec.GetDate,
                            UpdateDate = spec.UpdateDate,
                            Remark = spec.Remark
                        };
            var ret = query.FirstOrDefault();
            return ret;
        }

        public override OperationResult SaveExpertSpecialityInfo(tb_Expert_Speciality specModel)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            ret.ReturnValue = 0;
            ret.Message = "操作失败";
            try
            {
                var query = from dict in zbdlcontext.Dictionary
                            where dict.RootCode == "ExpSpec" && dict.IsDel == false
                            orderby dict.SortValue
                            select dict;
                List<T_Sys_Dict_Zbdlry> list = query.ToList();
                T_Sys_Dict_Zbdlry spec = list.Where(o => o.ParentSID == specModel.TypeFlags).FirstOrDefault();
                if (spec != null)
                {
                    var child = list.Where(o => o.ParentSID == spec.SID).FirstOrDefault();
                    if (child != null)
                    {
                        ret.Result = false;
                        ret.ReturnValue = 0;
                        ret.Message = "只能选择最后两级专业";
                        return ret;
                    }
                }
                if (specModel.ID == 0 && specModel.IsMain != null && specModel.IsMain == true)
                {
                    int cnt = zbdlcontext.ExpSpeciality.Where(o => o.IsMain == true && o.EmpGuid == specModel.EmpGuid && (o.IsDel == false || o.IsDel == null)).Count();
                    if (cnt > 0)
                    {
                        ret.Result = false;
                        ret.ReturnValue = 0;
                        ret.Message = "主专业已存在";
                        return ret;
                    }
                }
                else if (specModel.ID == 0 && specModel.IsMain != null && specModel.IsMain == false)
                {
                    int cnt = zbdlcontext.ExpSpeciality.Where(o => o.IsMain == false && o.EmpGuid == specModel.EmpGuid && (o.IsDel == false || o.IsDel == null)).Count();
                    if (cnt >= 2)
                    {
                        ret.Result = false;
                        ret.ReturnValue = 0;
                        ret.Message = "辅专业最多只能添加两项";
                        return ret;
                    }
                }

                if (!string.IsNullOrEmpty(specModel.SpecialityCode))
                {
                    int cnt = zbdlcontext.ExpSpeciality.Where(o => o.SpecialityCode == specModel.SpecialityCode && o.EmpGuid == specModel.EmpGuid && (o.IsDel == false || o.IsDel == null)).Count();
                    if (cnt > 0)
                    {
                        ret.Result = false;
                        ret.ReturnValue = 0;
                        ret.Message = "专业已存在";
                        return ret;
                    }
                }

                tb_Expert_Speciality_Zbdl specEntity = new tb_Expert_Speciality_Zbdl();
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(specModel, specEntity);
                specEntity.UpdateDate = DateTime.Now;
                specEntity.IsDel = false;
                zbdlcontext.Entry(specEntity).State = specEntity.ID == 0 ? EntityState.Added : EntityState.Modified;
                zbdlcontext.SaveChanges();
                ret.Message = "操作成功";
                ret.ReturnValue = 1;
                ret.Result = true;
            }
            catch (Exception err)
            {
                ret.Result = false;
                ret.Message = err.Message;
                ret.ReturnValue = 0;
            }
            return ret;
        }

        public override string GetSpecialityTitle(int sid)
        {
            string retmsg = string.Empty;
            var query = from dict in zbdlcontext.Dictionary
                        where dict.RootCode == "ExpSpec" && dict.IsDel == false
                        orderby dict.SortValue
                        select dict;
            List<T_Sys_Dict_Zbdlry> list = query.ToList();
            T_Sys_Dict_Zbdlry spec = list.Where(o => o.SID == sid).FirstOrDefault();
            if (spec != null)
            {
                retmsg = spec.Name;
                if (spec.ParentSID == 0)
                {
                    return retmsg;
                }
            }
            else
            {
                return retmsg;
            }
            while (spec.ParentSID != 0)
            {
                spec = list.Where(o => o.SID == spec.ParentSID).FirstOrDefault();
                if (spec != null)
                {
                    retmsg = spec.Name + "--" + retmsg;
                }
                else
                {
                    break;
                }
            }
            return retmsg;
        }

        public override OperationResult DeleteSpeciality(string specialityGuid)
        {
            DbSet<tb_Expert_Speciality_Zbdl> dbSpecs = zbdlcontext.ExpSpeciality;
            DTO.OperationResult result = new OperationResult();
            result.Message = "删除失败";
            result.Result = false;
            result.ReturnValue = 0;
            Guid sGuid = Guid.Empty;
            if (!Guid.TryParse(specialityGuid, out sGuid))
            {
                result.Result = false;
                result.Message = "专家专业参数不正确！";
                return result;
            }
            try
            {
                var spec = dbSpecs.Where(o => o.SpecialityGuid == sGuid).FirstOrDefault();
                if (spec != null)
                {
                    spec.IsDel = true;
                }
                zbdlcontext.SaveChanges();
                result.Message = "删除成功";
                result.Result = true;
                result.ReturnValue = 1;
            }
            catch (Exception ex)
            {
                result.Message = "删除失败" + ex.Message;
            }
            return result;
        }

        private DTO.tb_User_Relation GetUserRelationCorp(string userGuid, int classid, string entityName)
        {
            Guid guid = Guid.Empty;
            if (!Guid.TryParse(userGuid, out guid))
            {
                return null;
            }
            var query = from relation in zbdlcontext.UserRelation
                        where (relation.IsDel == false || relation.IsDel == null) && relation.UserGuid == guid
                        && relation.EntityFlag == 1 && relation.ClassId == classid
                        select new tb_User_Relation()
                        {
                            ID = relation.ID,
                            Gid = relation.Gid,
                            UserGuid = relation.UserGuid,
                            EntityGuid = relation.EntityGuid,
                            EntityFlag = relation.EntityFlag,
                            EntityID = relation.EntityID,
                            EntityName = relation.EntityName,
                            AppId = relation.AppId,
                            ClassId = relation.ClassId,
                            Reason = relation.Reason,
                            AreaCode = relation.AreaCode,
                            CreateTime = relation.CreateTime,
                            UpdateTime = relation.UpdateTime,
                            Remark = relation.Remark
                        };
            if (!string.IsNullOrEmpty(entityName))
            {
                query = query.Where(o => o.EntityName == entityName);
            }
            var ret = query.FirstOrDefault();
            return ret;
        }

        public override DTO.OperationResult UpdateUserRelationCorp(string userGuid, int classid, string entityName, string newName)
        {
            DTO.OperationResult result = new OperationResult();
            result.Message = "更新失败";
            result.Result = false;
            result.ReturnValue = 0;
            DTO.tb_User_Relation corpRel = GetUserRelationCorp(userGuid, classid, entityName);
            if (corpRel == null) { return result; }
            corpRel.EntityName = newName;
            corpRel.EntityGuid = Guid.NewGuid();
            result = SaveUserRelationInfo(corpRel);
            return result;
        }

        public override DTO.OperationResult DeleteUserRelationCorp(string userGuid, int classid, string entityName)
        {
            DTO.OperationResult result = new OperationResult();
            result.Message = "删除失败";
            result.Result = false;
            result.ReturnValue = 0;
            DTO.tb_User_Relation corpRel = GetUserRelationCorp(userGuid, classid, entityName);
            if (corpRel == null) { return result; }
            try
            {
                var relation = zbdlcontext.UserRelation.Where(o => o.Gid == corpRel.Gid).FirstOrDefault();
                if (relation != null)
                {
                    if (relation.ClassId != null && relation.ClassId == 1003)
                    {
                        result.Result = false;
                        result.Message = "注册单位不可删除!";
                        return result;
                    }
                    relation.IsDel = true;
                }
                zbdlcontext.SaveChanges();
                result.Message = "删除成功";
                result.Result = true;
                result.ReturnValue = 1;
            }
            catch (Exception ex)
            {
                result.Message = "删除失败" + ex.Message;
            }
            return result;
        }

        public override IList<DTO.tb_User_Relation> GetUserRelationList(string userGuid, int flag)
        {
            Guid guid = Guid.Empty;
            if (!Guid.TryParse(userGuid, out guid))
            {
                return null;
            }
            var query = from relation in zbdlcontext.UserRelation
                        where (relation.IsDel == false || relation.IsDel == null) && relation.UserGuid == guid
                        select new tb_User_Relation()
                        {
                            ID = relation.ID,
                            Gid = relation.Gid,
                            UserGuid = relation.UserGuid,
                            EntityGuid = relation.EntityGuid,
                            EntityFlag = relation.EntityFlag,
                            EntityID = relation.EntityID,
                            EntityName = relation.EntityName,
                            AppId = relation.AppId,
                            ClassId = relation.ClassId,
                            Reason = relation.Reason,
                            AreaCode = relation.AreaCode,
                            CreateTime = relation.CreateTime,
                            UpdateTime = relation.UpdateTime,
                            Remark = relation.Remark
                        };
            if (flag != -1)
            {
                query = query.Where(o => o.EntityFlag == flag);
            }
            query = query.OrderByDescending(o => o.UpdateTime);

            var ret = query.ToList();
            int count = ret.Count();
            var top = ret.Take(20).ToList();
            {
                foreach (var item in top)
                {
                    if (flag == 0)
                    {
                        var expert = zbdlcontext.Emp_Manager.Where(o => o.EmpGuid == item.EntityGuid).FirstOrDefault();
                        if (expert != null)
                        {
                            item.Remark = expert.IDCard;
                        }
                    }
                    else if (flag == 1)
                    {
                        item.Remark = GetUserRelationType(item.ClassId.ToString());
                    }
                }
            }
            return ret;
        }

        private string GetUserRelationType(string type)
        {
            string ret = string.Empty;
            switch (type)
            {
                case "1000":
                    ret = "添加单位";
                    break;
                case "1001":
                    ret = "添加单位";
                    break;
                case "1002":
                    ret = "工作单位";
                    break;
                case "1003":
                    ret = "注册单位";
                    break;
                default:
                    break;
            }
            return ret;
        }

        public override DTO.tb_User_Relation GetUserRelationInfo(string gid)
        {
            DbSet<tb_User_Relation_Zbdlry> dbRelation = zbdlcontext.UserRelation;
            Guid guid = Guid.Empty;
            if (!Guid.TryParse(gid, out guid))
            {
                return null;
            }
            var query = from relation in dbRelation
                        where relation.Gid == guid && (relation.IsDel == false || relation.IsDel == null)
                        select new tb_User_Relation()
                        {
                            ID = relation.ID,
                            Gid = relation.Gid,
                            UserGuid = relation.UserGuid,
                            EntityGuid = relation.EntityGuid,
                            EntityFlag = relation.EntityFlag,
                            EntityID = relation.EntityID,
                            EntityName = relation.EntityName,
                            AppId = relation.AppId,
                            ClassId = relation.ClassId,
                            Reason = relation.Reason,
                            AreaCode = relation.AreaCode,
                            CreateTime = relation.CreateTime,
                            UpdateTime = relation.UpdateTime
                        };
            var ret = query.FirstOrDefault();
            return ret;
        }

        public override OperationResult SaveUserRelationInfo(tb_User_Relation relationModel)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            ret.ReturnValue = 0;
            ret.Message = "操作失败";
            try
            {
                if (relationModel.EntityGuid != null)
                {
                    int cnt = zbdlcontext.UserRelation.Where(o => o.EntityGuid == relationModel.EntityGuid && o.UserGuid == relationModel.UserGuid && (o.IsDel == false || o.IsDel == null)).Count();
                    if (cnt > 0)
                    {
                        ret.Result = false;
                        ret.ReturnValue = 0;
                        ret.Message = "该关系已存在";
                        return ret;
                    }
                }
                if (!String.IsNullOrEmpty(relationModel.EntityName))
                {
                    int cnt = zbdlcontext.UserRelation.Where(o => o.EntityName == relationModel.EntityName && o.UserGuid == relationModel.UserGuid && (o.IsDel == false || o.IsDel == null)).Count();
                    if (cnt > 0)
                    {
                        ret.Result = false;
                        ret.ReturnValue = 0;
                        ret.Message = "该回避关系已存在";
                        return ret;
                    }
                }
                tb_User_Relation_Zbdlry relationEntity = new tb_User_Relation_Zbdlry();
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(relationModel, relationEntity);
                relationEntity.IsDel = false;
                relationEntity.UpdateTime = DateTime.Now;
                zbdlcontext.Entry(relationEntity).State = relationEntity.ID == 0 ? EntityState.Added : EntityState.Modified;
                zbdlcontext.SaveChanges();
                ret.Message = "操作成功";
                ret.ReturnValue = 1;
                ret.Result = true;
            }
            catch (Exception err)
            {
                ret.Result = false;
                ret.Message = err.Message;
                ret.ReturnValue = 0;
            }
            return ret;
        }

        public override OperationResult DeleteUserRelation(string gid)
        {
            DbSet<tb_User_Relation_Zbdlry> dbRelation = zbdlcontext.UserRelation;
            DTO.OperationResult result = new OperationResult();
            result.Message = "删除失败";
            result.Result = false;
            result.ReturnValue = 0;
            Guid Gid = Guid.Empty;
            if (!Guid.TryParse(gid, out Gid))
            {
                result.Result = false;
                result.Message = "专家专业参数不正确！";
                return result;
            }
            try
            {
                var relation = dbRelation.Where(o => o.Gid == Gid).FirstOrDefault();
                if (relation != null)
                {
                    if (relation.ClassId != null && relation.ClassId == 1003)
                    {
                        result.Result = false;
                        result.Message = "注册单位不可删除!";
                        return result;
                    }
                    else if (relation.ClassId != null && relation.ClassId == 1002)
                    {
                        result.Result = false;
                        result.Message = "单位不可删除!";
                        return result;
                    }
                    relation.IsDel = true;
                }
                zbdlcontext.SaveChanges();
                result.Message = "删除成功";
                result.Result = true;
                result.ReturnValue = 1;
            }
            catch (Exception ex)
            {
                result.Message = "删除失败" + ex.Message;
            }
            return result;
        }

        #endregion

        #region 专家信息管理
        public override IList<tb_Emp_Manager> GetExpertList(out int count, int pageNum, int pageSize, string conditions, string areaCode)
        {
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbuser = zbdlcontext.T_Sys_Users;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var dbSpec = zbdlcontext.ExpSpeciality;

            var query = from emps in dbEmp
                        join users in dbuser on emps.EmpGuid equals users.UserGuid
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid into empcorps
                        from empcorp in empcorps.DefaultIfEmpty()
                        join spec in dbSpec on new
                        {
                            EmpGuid = emps.EmpGuid,
                            IsMain = (bool?)true,
                            IsDel = (bool?)false
                        } equals new
                        {
                            EmpGuid = spec.EmpGuid,
                            IsMain = spec.IsMain,
                            IsDel = spec.IsDel
                        } into jSpecs
                        from empspecs in jSpecs.DefaultIfEmpty()
                        where emps.FlowAreaCode == areaCode && (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.DBType,
                            FlowCode = emps.RealFlowCode,
                            corpName = empcorp.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = empcorp.OrginazationCode,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            FlowAreaCode = emps.FlowAreaCode,
                            MainSpec = empspecs.SpecialityName,
                            MainSpecCode = empspecs.SpecialityCode,
                            DBType = emps.DBType
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions) && conditions.Count() > 0)
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            count = query.Count();
            query = query.OrderByDescending(o => o.ID).Skip((pageNum - 1) * pageSize).Take(pageSize);
            var result = query.ToList();
            foreach (var item in result)
            {
                try
                {
                    item.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                        item.FlowAreaCode,
                        "8065",
                        item.FlowCode);
                    item.DBType = new BasicBLL().GetExpertDBName(item.DBType);
                }
                catch (Exception ex)
                {

                }
            }
            return result;
        }

        public override int GetExpertCount(string conditions, string areaCode)
        {
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbuser = zbdlcontext.T_Sys_Users;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var query = from emps in dbEmp
                        join users in dbuser on emps.EmpGuid equals users.UserGuid
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid into empcorps
                        from empcorp in empcorps.DefaultIfEmpty()
                        where (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = empcorp.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = empcorp.OrginazationCode,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            FlowAreaCode = emps.FlowAreaCode
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions) && conditions.Count() > 0)
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            var result = query.Count();
            return result;
        }

        public override tb_Emp_Manager GetExpertInfo(string conditions, string areaCode)
        {
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbuser = zbdlcontext.T_Sys_Users;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbFlowCode = zbdlcontext.FlowCodes;
            var query = from emps in dbEmp
                        join users in dbuser on emps.EmpGuid equals users.UserGuid
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid into empcorps
                        from empcorp in empcorps.DefaultIfEmpty()
                        where (emps.IsDel == null || emps.IsDel == false)
                        && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = emps.RealFlowCode,
                            corpName = empcorp.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = empcorp.OrginazationCode,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            FlowAreaCode = emps.FlowAreaCode
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions) && conditions.Count() > 0)
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            var result = query.FirstOrDefault();
            return result;
        }

        public override DTO.OperationResult EditExpertInfo(DTO.tb_Emp_Manager expertModel)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            ret.ReturnValue = 0;
            ret.Message = "操作失败";
            try
            {
                tb_Emp_Manager_Zbdl expertEntity = new tb_Emp_Manager_Zbdl();
                expertEntity = zbdlcontext.Emp_Manager.Where(o => o.EmpGuid == expertModel.EmpGuid).FirstOrDefault();
                if (expertEntity == null)
                {
                    ret.Message = "找不到此人信息";
                }
                else
                {
                    Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(expertModel, expertEntity);
                    expertEntity.IsDel = false;
                    zbdlcontext.SaveChanges();
                    ret.Message = "修改成功";
                    ret.ReturnValue = 1;
                    ret.Result = true;
                }
            }
            catch (Exception err)
            {
                ret.Result = false;
                ret.Message = err.Message;
                ret.ReturnValue = 0;
            }
            return ret;
        }

        /// <summary>
        /// 上报，取消上报，审核，退回专家信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult ExpertInfoPost(string corpUserGuid, IList<string> emps, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (log == null)
            {
                result.Result = false;
                result.Message = "参数错误！";
                return result;
            }
            //参数不够使用log传递参数
            int optType = 4;
            int.TryParse(log.FunctionId, out optType);
            string message = log.FunctionType;
            string description = log.Notice;
            return ExpertInfoReportOrAudit(corpUserGuid, emps, optType, areaCode, message, description);
        }

        /// <summary>
        /// 专家上报、审核、退回
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="optType"></param>
        /// <param name="areaCode"></param>
        /// <param name="massage"></param>
        /// <returns></returns>
        private DTO.OperationResult ExpertInfoReportOrAudit(string corpUserGuid,
            IList<string> emps,
            int optType,
            string areaCode,
            string massage,
            string description)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string empName = "";
            ////用户验证
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result || result0.ReturnValue == null)
            {
                result.Result = false;
                result.Message = "登录用户信息有误！";
                return result;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            try
            {
                string msg = massage;
                foreach (var item in emps)
                {
                    ////判断人员是否存在
                    DTO.OperationResult result1 = CheckEmpIsExist(item.Trim());
                    if (!result1.Result)
                    {
                        result.Message += result1.Message;
                        continue;
                    }
                    tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result1.ReturnValue;
                    if (userInfo.RoleID != null && userInfo.RoleID == 87)
                    {
                        ////济南及其他市直直接退回
                        if (currentManager.DBType.StartsWith("01") || currentManager.DBType.EndsWith("01"))
                        {
                            if (currentManager.FlowCode.EndsWith("041"))
                            {
                                if (optType == 6)
                                {
                                    optType = 9;
                                }
                            }
                        }
                    }
                    ////取得审核状态
                    DTO.OperationResult result2 = CheckFlowCode(item.Trim(), optType, currentManager.ClassId, userInfo.RoleID.ToString(), areaCode, areaCode);
                    if (!result2.Result)
                    {
                        // result.Message += "您不能对人员" + currentManager.Name + "的执行此操作！";
                        continue;
                    }
                    string code = result2.ReturnValue.ToString();
                    if (string.IsNullOrEmpty(code))
                    {
                        continue;
                    }
                    ////修改审核状态
                    DTO.OperationResult result3 = EmpFlowCodeEdit(currentManager.EmpGuid.ToString(), currentManager.ClassId, areaCode, code, description);
                    EmpFlowCodeEdit(currentManager.EmpGuid, code);
                    // result.Message += currentManager.Name + result3.Message;
                    empName += currentManager.Name + ",";
                    result.Result = result3.Result;
                    ////日志
                    if (description.Length > 0)
                    {
                        massage = msg + "<br/>审核意见：" + description;
                    }
                    var flag = SetUserLog(massage, currentManager, "", optType.ToString(), areaCode, corpUserGuid);
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message += currentManager.Name + "日志写入出错！";
                    }
                }
                if (empName.Length > 1)
                {
                    result.Message += "专家[" + empName.TrimEnd(',') + "]操作执行成功！";
                }
                else
                {
                    result.Message += "操作执行失败，请确认选择人员的审核状态！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                if (empName.Length > 1)
                {
                    empName = empName.TrimEnd(',');
                    if (result.Message.IndexOf(empName) < 0)
                    {
                        result.Message += "专家[" + empName + "]操作执行成功！";
                    }
                }
                result.Message = massage + "失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }
        #endregion

        #region 报名考试

        #region 期次
        /// <summary>
        /// 获取期次列表
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="appid">系统id</param>
        /// <param name="pageIndex">当前页数</param>
        /// <param name="pageSize">一页数量</param>
        /// <param name="dataCount">列表数量</param>
        /// <returns></returns>
        public override IList<DTO.Exam_QC> GetExamQCList(
            string sql,
            string appId,
            int pageIndex,
            int pageSize,
            out int dataCount)
        {
            dataCount = 0;
            try
            {
                List<Entity.ZBDLRY.Exam_QC> list = new PersonDALWh().GetExamQCList(
                    sql,
                    appId,
                    pageIndex,
                    pageSize,
                    out dataCount);
                List<DTO.Exam_QC> lists = new List<DTO.Exam_QC>();
                foreach (Entity.ZBDLRY.Exam_QC item in list)
                {
                    DTO.Exam_QC qc = new DTO.Exam_QC();
                    EntityHelper.ConvertEntity2OtherEntity(item, qc);
                    lists.Add(qc);
                }
                return lists;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 添加期次
        /// </summary>
        /// <param name="qc"></param>
        /// <returns></returns>
        public override OperationResult AddExamQC(DTO.Exam_QC qc)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            try
            {
                var exam = zbdlcontext.ExamQC.Where(q => q.Title == qc.Title && q.Code == qc.Code
                    && q.AppId == qc.AppId && q.IsDel == false).FirstOrDefault();
                if (exam != null)
                {
                    result.Message = "该期次已存在！";
                }
                else
                {
                    Entity.ZBDLRY.Exam_QC examqc = new Entity.ZBDLRY.Exam_QC();
                    EntityHelper.ConvertEntity2OtherEntity(qc, examqc);
                    zbdlcontext.ExamQC.Add(examqc);
                    zbdlcontext.SaveChanges();
                    result.Message = "添加成功！";
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 修改期次
        /// </summary>
        /// <param name="qc"></param>
        /// <returns></returns>
        public override OperationResult EditExamQC(DTO.Exam_QC qc)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.Message = "操作失败!";
            try
            {
                var exam = zbdlcontext.ExamQC.Where(q => q.Title == qc.Title && q.Code == qc.Code
                        && q.AppId == qc.AppId && q.IsDel == false && q.ID != qc.ID).FirstOrDefault();
                if (exam != null)
                {
                    result.Message = "该期次已存在！";
                }
                else
                {
                    var examqc = zbdlcontext.ExamQC.Where(q => q.ID == qc.ID).SingleOrDefault();
                    if (examqc != null)
                    {
                        EntityHelper.ConvertEntity2OtherEntity(qc, examqc);
                        zbdlcontext.SaveChanges();
                        result.Message = "修改成功！";
                        result.Result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "修改失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除期次
        /// </summary>
        /// <param name="qcid"></param>
        /// <returns></returns>
        public override OperationResult DeleteExamQC(int qcId)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.Message = "操作失败!";
            try
            {
                var examqc = zbdlcontext.ExamQC.Where(q => q.ID == qcId).SingleOrDefault();
                if (examqc != null)
                {
                    examqc.IsDel = true;
                    zbdlcontext.SaveChanges();
                    result.Message = "删除成功！";
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取期次详细信息
        /// </summary>
        /// <param name="qcid"></param>
        /// <returns></returns>
        public override DTO.Exam_QC GetExamQC(int qcId)
        {
            DTO.Exam_QC qc = new DTO.Exam_QC();
            var examqc = zbdlcontext.ExamQC.Where(q => q.ID == qcId).FirstOrDefault();
            if (examqc != null)
            {
                EntityHelper.ConvertEntity2OtherEntity(examqc, qc);
            }
            return qc;
        }
        #endregion

        #region 科目
        /// <summary>
        /// 获取科目列表
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="appId"></param>
        /// <param name="qcId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public override IList<DTO.Exam_KM> GetExamKMList(
            string sql,
            string appId,
            string qcId,
            int pageIndex,
            int pageSize,
            out int dataCount)
        {
            dataCount = 0;
            try
            {
                List<Entity.ZBDLRY.Exam_KM> list = new PersonDALWh().GetExamKMList(
                    sql,
                    appId,
                    qcId,
                    pageIndex,
                    pageSize,
                    out dataCount);
                List<DTO.Exam_KM> lists = new List<DTO.Exam_KM>();
                foreach (Entity.ZBDLRY.Exam_KM item in list)
                {
                    DTO.Exam_KM km = new DTO.Exam_KM();
                    EntityHelper.ConvertEntity2OtherEntity(item, km);
                    lists.Add(km);
                }
                return lists;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 添加科目
        /// </summary>
        /// <param name="km"></param>
        /// <returns></returns>
        public override OperationResult AddExamKM(DTO.Exam_KM km)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            try
            {
                var exam = zbdlcontext.ExamKM.Where(q => q.Title == km.Title && q.QCId == km.QCId && q.IsDel == false).FirstOrDefault();
                if (exam != null)
                {
                    result.Message = "该期次下科目已存在！";
                }
                else
                {
                    Entity.ZBDLRY.Exam_KM examkm = new Entity.ZBDLRY.Exam_KM();
                    EntityHelper.ConvertEntity2OtherEntity(km, examkm);
                    zbdlcontext.ExamKM.Add(examkm);
                    zbdlcontext.SaveChanges();
                    result.Message = "添加成功！";
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 修改科目
        /// </summary>
        /// <param name="km"></param>
        /// <returns></returns>
        public override OperationResult EditExamKM(DTO.Exam_KM km)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.Message = "操作失败!";
            try
            {
                var exam = zbdlcontext.ExamKM.Where(q => q.Title == km.Title && q.QCId == km.QCId && q.IsDel == false && q.ID != km.ID).FirstOrDefault();
                if (exam != null)
                {
                    result.Message = "该期次下科目已存在！";
                }
                else
                {
                    var examkm = zbdlcontext.ExamKM.Where(q => q.ID == km.ID).SingleOrDefault();
                    if (examkm != null)
                    {
                        examkm.Title = km.Title;
                        examkm.PassScore = km.PassScore;
                        examkm.QCId = km.QCId;
                        examkm.ExamLength = km.ExamLength;
                        zbdlcontext.SaveChanges();
                        result.Message = "修改成功！";
                        result.Result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "修改失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除科目
        /// </summary>
        /// <param name="kmid"></param>
        /// <returns></returns>
        public override OperationResult DeleteExamKM(int kmId)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.Message = "操作失败!";
            try
            {
                var examkm = zbdlcontext.ExamKM.Where(q => q.ID == kmId).SingleOrDefault();
                if (examkm != null)
                {
                    examkm.IsDel = true;
                    zbdlcontext.SaveChanges();
                    result.Message = "删除成功！";
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取科目详细信息
        /// </summary>
        /// <param name="kmid"></param>
        /// <returns></returns>
        public override DTO.Exam_KM GetExamKM(int kmId)
        {
            DTO.Exam_KM qc = new DTO.Exam_KM();
            var examkm = zbdlcontext.ExamKM.Where(q => q.ID == kmId).FirstOrDefault();
            if (examkm != null)
            {
                EntityHelper.ConvertEntity2OtherEntity(examkm, qc);
            }
            return qc;
        }
        #endregion

        #region 考场

        /// <summary>
        /// 获取考场列表
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="qcId"></param>
        /// <param name="kmId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public override IList<DTO.Exam_Room> GetExamKCList(
            string sql,
            string appId,
            string qcId,
            string kmId,
            int pageIndex,
            int pageSize,
            out int dataCount)
        {
            dataCount = 0;
            try
            {
                List<Entity.ZBDLRY.Exam_Room> list = new PersonDALWh().GetExamKCList(
                    sql,
                    appId,
                    qcId,
                    kmId,
                    pageIndex,
                    pageSize,
                    out dataCount);
                List<DTO.Exam_Room> lists = new List<DTO.Exam_Room>();
                foreach (Entity.ZBDLRY.Exam_Room item in list)
                {
                    DTO.Exam_Room kc = new DTO.Exam_Room();
                    EntityHelper.ConvertEntity2OtherEntity(item, kc);
                    lists.Add(kc);
                }
                return lists;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 添加考场
        /// </summary>
        /// <param name="kc"></param>
        /// <returns></returns>
        public override OperationResult AddExamKC(DTO.Exam_Room kc)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            try
            {
                ////考场Title和Code唯一
                var exam = zbdlcontext.ExamRoom.Where(q => (q.Title == kc.Title || q.Code == kc.Code) && q.QCId == kc.QCId
                    && q.KMId == kc.KMId && q.IsDel == false).FirstOrDefault();
                if (exam != null)
                {
                    result.Message = "该考场已存在！";
                }
                else
                {
                    Entity.ZBDLRY.Exam_Room examkc = new Entity.ZBDLRY.Exam_Room();
                    EntityHelper.ConvertEntity2OtherEntity(kc, examkc);
                    zbdlcontext.ExamRoom.Add(examkc);
                    zbdlcontext.SaveChanges();
                    result.Message = "添加成功！";
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 修改考场
        /// </summary>
        /// <param name="kc"></param>
        /// <returns></returns>
        public override OperationResult EditExamKC(DTO.Exam_Room kc)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.Message = "操作失败!";
            try
            {
                ////考场安排考生后不能修改考场信息
                var emps = zbdlcontext.ExamEmpRoom.Where(k => k.KCId == kc.ID).Count();
                if (emps > 0)
                {
                    result.Message = "该考场下已安排考生，不能修改!";
                    return result;
                }
                var exam = zbdlcontext.ExamRoom.Where(q => (q.Title == kc.Title || q.Code == kc.Code) && q.QCId == kc.QCId
                     && q.KMId == kc.KMId && q.IsDel == false && q.ID != kc.ID).FirstOrDefault();
                if (exam != null)
                {
                    result.Message = "该考场已存在！";
                }
                else
                {
                    var examkc = zbdlcontext.ExamRoom.Where(q => q.ID == kc.ID).SingleOrDefault();
                    if (examkc != null)
                    {
                        examkc.Title = kc.Title;
                        examkc.Code = kc.Code;
                        examkc.Number = kc.Number;
                        examkc.QCId = kc.QCId;
                        examkc.ExamDate = kc.ExamDate;
                        examkc.ExamAddress = kc.ExamAddress;
                        examkc.KMId = kc.KMId;
                        examkc.CityCode = kc.CityCode;
                        zbdlcontext.SaveChanges();
                        result.Message = "修改成功！";
                        result.Result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "修改失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除考场
        /// </summary>
        /// <param name="kcid"></param>
        /// <returns></returns>
        public override OperationResult DeleteExamKC(int kcId)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.Message = "操作失败!";
            try
            {
                var examkc = zbdlcontext.ExamRoom.Where(q => q.ID == kcId).SingleOrDefault();
                if (examkc != null)
                {
                    examkc.IsDel = true;
                    zbdlcontext.SaveChanges();
                    result.Message = "删除成功！";
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取考场详细信息
        /// </summary>
        /// <param name="kcid"></param>
        /// <returns></returns>
        public override DTO.Exam_Room GetExamKC(int kcId)
        {
            DTO.Exam_Room kc = new DTO.Exam_Room();
            var examkc = zbdlcontext.ExamRoom.Where(q => q.ID == kcId).FirstOrDefault();
            if (examkc != null)
            {
                EntityHelper.ConvertEntity2OtherEntity(examkc, kc);
            }
            return kc;
        }

        /// <summary>
        /// 考场座次安排
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="appId"></param>
        /// <param name="kcId"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public override List<DTO.ExamEmpRoom> GetKCZCList(
            string sql,
            string appId,
            int kcId,
            string corpUserGuid,
            int pageIndex,
            int pageSize,
            out int dataCount)
        {
            dataCount = 0;
            try
            {
                List<Entity.ZBDLRY.ExamEmpRoom> list = new PersonDALWh().GetKCZCList(
                    sql,
                    appId,
                    kcId,
                    corpUserGuid,
                    pageIndex,
                    pageSize,
                    out dataCount);
                ////该考场下的座位数
                var number = zbdlcontext.ExamRoom.Where(m => m.ID == kcId).FirstOrDefault().Number;
                List<DTO.ExamEmpRoom> lists = new List<DTO.ExamEmpRoom>();
                foreach (Entity.ZBDLRY.ExamEmpRoom item in list)
                {
                    DTO.ExamEmpRoom kc = new DTO.ExamEmpRoom();
                    EntityHelper.ConvertEntity2OtherEntity(item, kc);
                    lists.Add(kc);
                }
                if (number == lists.Count())
                {
                    return lists;
                }
                else
                {
                    ////座次自动填充
                    List<DTO.ExamEmpRoom> newList = new List<DTO.ExamEmpRoom>();
                    if (lists.Count() > 0)
                    {
                        for (int i = 0; i < lists.Count(); i++)
                        {
                            int c = newList.Count();
                            int newCode = 0;
                            if (c != 0)
                            {
                                int.TryParse(newList[c - 1].SeatCode, out newCode);
                            }
                            int oldCode = int.Parse(lists[i].SeatCode);
                            for (int j = newCode + 1; j < oldCode; j++)
                            {
                                DTO.ExamEmpRoom room = new DTO.ExamEmpRoom();
                                room.SeatCode = j.ToString("00");
                                newList.Add(room);
                            }
                            newList.Add(lists[i]);
                        }
                    }
                    if (number != newList.Count())
                    {
                        for (int i = newList.Count(); i < number; i++)
                        {
                            DTO.ExamEmpRoom room = new DTO.ExamEmpRoom();
                            room.SeatCode = (i + 1).ToString("00");
                            newList.Add(room);
                        }
                    }
                    return newList;
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region 报名

        /// <summary>
        ///  获取报名列表
        /// </summary>
        public override List<DTO.ExamInfo> GetExamBMList(
            string sql,
            string appId,
            int qcId,
            string areaCode,
            DTO.tb_Emp_Manager emp,
            int requestType,
            int pageIndex,
            int pageSize,
            out int dataCount)
        {
            dataCount = 0;
            try
            {
                List<Entity.ZBDLRY.ExamInfo> list = new PersonDALWh().GetExamBMList(
                    sql,
                    appId,
                    qcId,
                    areaCode,
                    emp,
                    requestType,
                    pageIndex,
                    pageSize,
                    out dataCount);
                List<DTO.ExamInfo> lists = new List<DTO.ExamInfo>();
                foreach (Entity.ZBDLRY.ExamInfo item in list)
                {
                    DTO.ExamInfo km = new DTO.ExamInfo();
                    EntityHelper.ConvertEntity2OtherEntity(item, km);
                    lists.Add(km);
                }
                return lists;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取企业下已报名人员
        /// </summary>
        public override ExamBM GetBMEmpList(int treeId)
        {
            ExamBM examBm = new ExamBM();
            var info = (from exam in zbdlcontext.ExamInfo
                        join qc in zbdlcontext.ExamQC on exam.QCId equals qc.ID
                        where exam.IsDel == false && exam.ID == treeId
                        select new
                        {
                            exam.ID,
                            exam.QCId,
                            qc.Title,
                            exam.AreaCode,
                            exam.CorpUserGuid,
                            exam.CorpName,
                            exam.BMDate,
                            qc.EndDate,
                            qc.StartDate
                        }).FirstOrDefault();
            if (info != null)
            {
                examBm.ID = info.ID;
                examBm.QCId = info.QCId;
                examBm.QCTitle = info.Title;
                examBm.AreaCode = info.AreaCode;
                examBm.CorpUserGuid = info.CorpUserGuid;
                examBm.CorpName = info.CorpName;
                examBm.BMDate = info.BMDate;
                examBm.StartDate = info.StartDate;
                examBm.EndDate = info.EndDate;
                var sublist = from sub in zbdlcontext.ExamSubInfo
                              where sub.IsDel == false && sub.TreeId == treeId
                              select new ExamBMSub
                              {
                                  ID = sub.ID,
                                  TreeId = sub.TreeId,
                                  EmpGuid = sub.EmpGuid,
                                  ExamCertCode = sub.ExamCertCode,
                                  EmpName = sub.EmpName,
                                  IDCard = sub.IDCard
                              };
                List<ExamBMSub> bmSub = sublist.ToList();
                examBm.ExamBMSub = bmSub;
            }
            return examBm;
        }

        /// <summary>
        /// 添加报名
        /// </summary>
        public override OperationResult AddBMInfo(ExamBM bmInfo)
        {
            OperationResult result = new OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)zbdlcontext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    var bm = from bms in zbdlcontext.ExamInfo
                             where bms.QCId == bmInfo.QCId && bms.CorpUserGuid == bmInfo.CorpUserGuid && bms.IsDel == false
                             select bms;
                    if (bm.Count() > 0)
                    {
                        result.Result = false;
                        result.Message = "该期次已报名！";
                    }
                    else
                    {
                        Entity.ZBDLRY.Exam_Info info = new Entity.ZBDLRY.Exam_Info();
                        EntityHelper.ConvertEntity2OtherEntity(bmInfo, info);
                        zbdlcontext.ExamInfo.Add(info);
                        zbdlcontext.SaveChanges();
                        var ids = from exam in zbdlcontext.ExamInfo
                                  where exam.CorpUserGuid == bmInfo.CorpUserGuid
                                  orderby exam.ID descending
                                  select exam.ID;
                        bmInfo.ID = ids.FirstOrDefault();
                        foreach (ExamBMSub item in bmInfo.ExamBMSub)
                        {
                            item.TreeId = bmInfo.ID;
                            Entity.ZBDLRY.Exam_SubInfo subInfo = new Entity.ZBDLRY.Exam_SubInfo();
                            EntityHelper.ConvertEntity2OtherEntity(item, subInfo);
                            zbdlcontext.ExamSubInfo.Add(subInfo);
                        }
                        zbdlcontext.SaveChanges();
                        result.Result = true;
                        result.Message = "报名成功";
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    result.Message = "报名失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 修改考试报名
        /// </summary>
        public override OperationResult EditBMInfo(ExamBM bmInfo)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.Message = "操作失败！";
            using (DbConnection con = ((IObjectContextAdapter)zbdlcontext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    var qc = (from q in zbdlcontext.ExamQC
                              where q.ID == bmInfo.QCId
                              select q).SingleOrDefault();
                    if (qc.EndDate < DateTime.Parse(DateTime.Now.ToShortDateString()))
                    {
                        result.Message = "该期次报名已截止！";
                    }
                    else
                    {
                        var bm = zbdlcontext.ExamInfo.Where(c => c.ID == bmInfo.ID).SingleOrDefault();
                        if (bm != null)
                        {
                            var newList = bmInfo.ExamBMSub;//报名新列表
                            var oldList = zbdlcontext.ExamSubInfo.Where(c => c.TreeId == bmInfo.ID).ToList();//之前报名信息
                            for (int i = 0; i < newList.Count; i++)
                            {
                                for (int j = 0; j < oldList.Count; j++)
                                {
                                    if (newList[i].EmpGuid == oldList[j].EmpGuid) //已经存在的数据修改isdel
                                    {
                                        oldList[j].IsDel = false;
                                        break;
                                    }
                                    else if (j == oldList.Count - 1)//不存在数据新增
                                    {
                                        Entity.ZBDLRY.Exam_SubInfo InfoSub = new Entity.ZBDLRY.Exam_SubInfo();
                                        EntityHelper.ConvertEntity2OtherEntity(newList[i], InfoSub);
                                        zbdlcontext.ExamSubInfo.Add(InfoSub);
                                    }
                                }
                            }
                            for (int i = 0; i < oldList.Count; i++)
                            {
                                for (int j = 0; j < newList.Count; j++)
                                {
                                    if (newList[j].EmpGuid == oldList[i].EmpGuid)
                                    {
                                        oldList[i].IsDel = false;
                                        break;
                                    }
                                    else if (j == newList.Count - 1)//删除
                                    {
                                        oldList[i].IsDel = true;
                                    }
                                }
                            }
                            zbdlcontext.SaveChanges();
                            result.Result = true;
                            result.Message = "修改成功！";
                        }
                        tran.Commit();
                    }
                }
                catch (Exception ex)
                {
                    result.Message = "修改失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 取消报名
        /// </summary>
        /// <param name="bmID">报名主表ID</param>
        public override OperationResult CancelBMInfo(int bmID)
        {
            OperationResult result = new OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)zbdlcontext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    var bmInfo = zbdlcontext.ExamInfo.FirstOrDefault(e => e.ID == bmID);
                    if (bmInfo == null)
                    {
                        result.Result = false;
                        result.Message = "报名信息不存在！";
                    }
                    else
                    {
                        bmInfo.IsDel = true;
                        zbdlcontext.SaveChanges();

                        var subCollection = zbdlcontext.ExamSubInfo.Where(sub => sub.TreeId == bmID);
                        foreach (Exam_SubInfo item in subCollection)
                        {
                            item.IsDel = true;
                        }
                        zbdlcontext.SaveChanges();
                        result.Result = true;
                        result.Message = "取消报名成功";
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    result.Message = "取消报名失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 支付考试费用
        /// </summary>
        /// <param name="payInfo">支付信息</param>
        /// <param name="qcID">期次ID</param>
        public override OperationResult PayExamFee(DTO.PayInfo payInfo, int qcID)
        {
            OperationResult result = new OperationResult();

            ////判断是否已缴费
            result = IsExamFeePaid(qcID, payInfo.CorpUserGuid);
            if (result.Result)
            {
                result.Message = "当前期次已缴费，无法再次操作。";
                result.Result = false;
                return result;
            }

            #region 添加缴费判断日志
            UserLogManager.Log(new User_Log()
            {
                Content = "判断是否缴费",
                ObjectId = payInfo.Code,
                IsrtUser = payInfo.CorpUserGuid.ToString(),
                FunctionId = "IsExamFeePaid",
                FunctionType = ((int)DTO.FuncType.Add).ToString(),
                IsrtDate = DateTime.Now
            });
            #endregion

            using (DbConnection con = ((IObjectContextAdapter)zbdlcontext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Entity.ZBDLRY.tb_PayInfo tbPayInfo = new Entity.ZBDLRY.tb_PayInfo();
                    EntityHelper.ConvertEntity2OtherEntity(payInfo, tbPayInfo);
                    zbdlcontext.PayInfo.Add(tbPayInfo);
                    zbdlcontext.SaveChanges();

                    var pIdQuery = from pInfo in zbdlcontext.PayInfo
                                   where pInfo.KeyGUID == payInfo.KeyGUID
                                   select pInfo.ID;
                    payInfo.ID = pIdQuery.FirstOrDefault();
                    switch (payInfo.GroupCode.ToUpper())
                    {
                        case "EXP":
                            result = new OrderBLL().AddCommonSubOrder(payInfo);
                            break;
                        default:
                            result = null;
                            break;
                    }

                    Exam_Info exam = zbdlcontext.ExamInfo.FirstOrDefault(e => e.QCId == qcID && e.CorpUserGuid == payInfo.CorpUserGuid);
                    exam.OrderCode = payInfo.Code;
                    zbdlcontext.SaveChanges();

                    if (result != null && result.Result)
                    {
                        #region 添加操作日志
                        UserLogManager.Log(new User_Log()
                        {
                            Content = "专家缴费",
                            ObjectId = payInfo.KeyGUID.ToString(),
                            IsrtUser = payInfo.CorpUserGuid.ToString(),
                            FunctionId = "Expert",
                            FunctionType = ((int)DTO.FuncType.Add).ToString(),
                            IsrtDate = DateTime.Now
                        });
                        #endregion
                        tran.Commit();
                        result.Message = "缴费信息提交成功。";
                    }
                    else
                    {
                        tran.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    result.Message = "缴费信息提交失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 判断指定的期次是否已缴费
        /// </summary>
        /// <param name="qcID">指定的期次ID</param>
        /// <param name="userGuid">报名人的UserGuid</param>
        public override OperationResult IsExamFeePaid(int qcID, Guid userGuid)
        {
            OperationResult result = new OperationResult();
            var payInfo = (from exam in zbdlcontext.ExamInfo
                           join pay in zbdlcontext.PayInfo
                           on exam.OrderCode equals pay.Code
                           where exam.QCId == qcID && exam.CorpUserGuid == userGuid
                           select pay).FirstOrDefault();

            if (payInfo != null && payInfo.bPayStatus == 3)
            {
                result.Result = true;
            }
            else
            {
                result.Result = false;
                result.Message = "当前考试未缴费";
            }
            return result;
        }

        /// <summary>
        /// 更换考试报名列表
        /// </summary>
        public override List<ExamChangeEmp> GetBMChangeEmpList(
            int id,
            string appId,
            int pageIndex,
            int pageSize,
            out int dataCount)
        {
            var list = from info in zbdlcontext.ExamInfo
                       join qc in zbdlcontext.ExamQC on info.QCId equals qc.ID
                       join sub in zbdlcontext.ExamSubInfo on info.ID equals sub.TreeId
                       join change in zbdlcontext.ExamChangeEmp on sub.ID equals change.ExamSubId into emps
                       from changeemp in emps.DefaultIfEmpty()
                       where info.IsDel == false && sub.IsDel == false && (changeemp.IsDel == false || changeemp.IsDel == null) && qc.AppId == appId
                       select new DTO.ExamChangeEmp
                       {
                           ID = sub.ID,
                           QCId = info.QCId,
                           TreeId = sub.TreeId,
                           CorpUserGuid = info.CorpUserGuid,
                           QCTitle = qc.Title,
                           CorpName = info.CorpName,
                           EmpGuid = sub.EmpGuid,
                           EmpName = sub.EmpName,
                           IDCard = sub.IDCard,
                           AfterGuid = changeemp.AfterGuid,
                           AfterName = changeemp.AfterName,
                           Reason = changeemp.Reason
                       };
            if (id > 0)
            {
                list = list.Where(m => m.TreeId == id);
            }
            dataCount = list.Count();
            if (pageIndex == 0 && pageSize == 0)
            {
                return list.ToList();
            }
            else
            {
                return list.OrderBy(q => q.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }

        /// <summary>
        /// 添加考试更换人员信息
        /// </summary>
        public override OperationResult BMChangeEmp(DTO.Exam_ChangeEmp change)
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            try
            {
                var exam = zbdlcontext.ExamChangeEmp.Where(e => e.ExamSubId == change.ExamSubId && e.BeforeGuid == change.BeforeGuid && e.IsDel == false).FirstOrDefault();
                if (exam != null)
                {
                    exam.IsDel = true;
                }
                Entity.ZBDLRY.Exam_ChangeEmp examchange = new Entity.ZBDLRY.Exam_ChangeEmp();
                EntityHelper.ConvertEntity2OtherEntity(change, examchange);
                zbdlcontext.ExamChangeEmp.Add(examchange);
                zbdlcontext.SaveChanges();
                result.Message = "更换成功！";
                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Message = "更换失败：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 报名统计
        /// </summary>
        public override DataTable BMStatistics(string sql, string appId, int qcId, string areaCode)
        {
            return new PersonDALWh().BMStatistics(sql, appId, qcId, areaCode);
        }

        /// <summary>
        /// 获取专家属于的【纳入考试人员】的类型 1 | 2
        /// </summary>
        /// <param name="userGuid">专家Guid</param>
        public override string GetExpertExamType(Guid userGuid)
        {
            return new PersonDALWh().GetExpertExamType(userGuid);
        }

        #endregion

        #region 成绩

        public override OperationResult GetScoreList(string sql,
            string corpUserGuid,
            string appId,
            int qcId,
            int pageIndex,
            int pageSize,
            out int dataCount)
        {
            dataCount = 0;
            OperationResult result = new OperationResult();
            result.Result = false;
            result.ReturnValue = null;
            try
            {
                var query = zbdlcontext.ExamScore.Where(s => s.QCId == qcId && s.IsDel == false).Count();
                if (query > 0)
                {
                    result.ReturnValue = new PersonDALWh().GetScoreList(
                        sql,
                        corpUserGuid,
                        appId,
                        qcId,
                        pageIndex,
                        pageSize,
                        out  dataCount);
                    result.Result = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

        #endregion

        #region 准考证

        /// <summary>
        /// 获取准考证列表
        /// </summary>
        /// <param name="sql">拼接语句</param>
        /// <param name="appId">项目id</param>
        /// <param name="qcId">期次id</param>
        /// <param name="areaCode">地区号</param>
        /// <param name="corpName">单位名称</param>
        /// <param name="corpUserGuid">单位guid</param>
        /// <param name="empName">人员名称</param>
        /// <param name="ids">报名子表id集合</param>
        /// <param name="pageIndex">当前页数</param>
        /// <param name="pageSize">一页数量</param>
        /// <param name="dataCount">结果集数量</param>
        /// <returns>准考证集合</returns>
        public override List<DTO.Exam_ZKZ> GetZKZList(
          string sql,
          string appId,
          int qcId,
          string areaCode,
          string corpName,
          string corpUserGuid,
          string empName,
          string ids,
          int pageIndex,
          int pageSize,
          out int dataCount)
        {
            dataCount = 0;
            try
            {
                List<Entity.ZBDLRY.Exam_ZKZ> list = new PersonDALWh().GetZKZList(
                    sql,
                    appId,
                    qcId,
                    areaCode,
                    corpName,
                    corpUserGuid,
                    empName,
                    ids,
                    pageIndex,
                    pageSize,
                    out  dataCount);
                ////Entity转DTO
                List<DTO.Exam_ZKZ> lists = new List<DTO.Exam_ZKZ>();
                foreach (Entity.ZBDLRY.Exam_ZKZ item in list)
                {
                    DTO.Exam_ZKZ km = new DTO.Exam_ZKZ();
                    EntityHelper.ConvertEntity2OtherEntity(item, km);
                    ////接收到id集合，说明是内页，需要获取考场和科目信息
                    if (!string.IsNullOrEmpty(ids))
                    {
                        ////获取该考生的考试科目和考场信息
                        List<Entity.ZBDLRY.ExamEmpRoom> roomList = new PersonDALWh().GetKCZCList(item.ID);
                        List<DTO.ExamEmpRoom> roomLists = new List<DTO.ExamEmpRoom>();
                        foreach (Entity.ZBDLRY.ExamEmpRoom items in roomList)
                        {
                            DTO.ExamEmpRoom room = new DTO.ExamEmpRoom();
                            EntityHelper.ConvertEntity2OtherEntity(items, room);
                            roomLists.Add(room);
                        }
                        km.KMList = roomLists;
                    }
                    lists.Add(km);
                }
                return lists;
            }
            catch
            {
                return null;
            }
        }

        #endregion

        #endregion

        #region 项目负责人在建项目查询

        /// <summary>
        /// 获取项目负责人相关信息
        /// </summary>
        /// <param name="EmpGuid">GUID --貌似这个没有存在的必要</param>
        /// <param name="name">负责人名</param>
        /// <param name="idCard">身份证号</param>
        /// <param name="certificateCode">资格证号</param>
        public override string GetPMUnderConstruction(string name, string idCard, string certificateCode, string corpName, string areaCode)
        {
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbEmpPost = zbdlcontext.Emp_Post;
            var dbTitles = zbdlcontext.Emp_Qualities;
            var empGuids = new List<Guid>();
            string titleCode = string.Empty;//资格证书号的拼接字符串 用于判断该号是否已出现过
            ManagerProjectInfoDTO manager;
            List<ManagerProjectInfoDTO> managers = new List<ManagerProjectInfoDTO>();
            PersonDALWh personDal = new PersonDALWh();

            #region 1.查询满足条件的用户guid

            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        join post in dbEmpPost on new
                        {
                            EmpGuid = emps.EmpGuid,
                            IsDel = (bool?)false
                        } equals new
                        {
                            EmpGuid = post.EmpGuid,
                            IsDel = post.IsDel
                        }
                        into jPosts
                        from posts in jPosts.DefaultIfEmpty()
                        join title in dbTitles on new
                        {
                            EmpGuid = (Guid?)emps.EmpGuid,
                            IsDel = (bool?)false
                        }
                        equals new
                        {
                            EmpGuid = title.EmpGuid,
                            IsDel = title.IsDel
                        }
                        into jTitles
                        from titles in jTitles.DefaultIfEmpty()
                        where (emps.IsDel == null || emps.IsDel == false)
                            && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            IDCard = emps.IDCard,
                            Name = emps.Name,
                            CertificateCode = titles.CertificateCode,
                            corpName = companies.CorpName
                            #endregion
                        };
            #endregion

            #region 2.查询条件

            if (!string.IsNullOrEmpty(areaCode))
            {
                query = query.Where(q => q.AreaCode.StartsWith(areaCode));
            }

            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(q => q.Name == name);
            }

            if (!string.IsNullOrEmpty(idCard))
            {
                query = query.Where(q => q.IDCard == idCard);
            }

            if (!string.IsNullOrEmpty(certificateCode))
            {
                query = query.Where(q => q.CertificateCode == certificateCode);
            }

            if (!string.IsNullOrEmpty(corpName))
            {
                query = query.Where(q => q.corpName == corpName);
            }

            // 过滤多证重复人员
            empGuids = query.Select(q => q.EmpGuid).Distinct().ToList();

            #endregion

            #region 3.查询人员信息
            var query1 = from emps in dbEmp
                         join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                         join post in dbEmpPost on new
                         {
                             EmpGuid = emps.EmpGuid,
                             IsDel = (bool?)false
                         } equals new
                         {
                             EmpGuid = post.EmpGuid,
                             IsDel = post.IsDel
                         } into jPosts
                         from posts in jPosts.DefaultIfEmpty()
                         join title in dbTitles on new
                         {
                             EmpGuid = (Guid?)emps.EmpGuid,
                             IsDel = (bool?)false
                         }
                         equals new
                         {
                             EmpGuid = title.EmpGuid,
                             IsDel = title.IsDel
                         } into jTitles
                         from titles in jTitles.DefaultIfEmpty()
                         where empGuids.Contains(emps.EmpGuid)
                            && (emps.IsDel == null || emps.IsDel == false)
                            && (emps.FlowIsDel == false || emps.FlowIsDel == null)
                         select new tb_Emp_Manager()
                         {
                             EmpGuid = emps.EmpGuid,
                             AreaCode = emps.AreaCode,
                             IDCard = emps.IDCard,
                             Name = emps.Name,
                             CertificateCode = titles.CertificateCode,
                             CertificateName = titles.CertificateName
                         };
            var result = query1.OrderBy(q => q.EmpGuid).ToList();

            #endregion

            #region 4.封装数据。

            foreach (var m in result)
            {
                manager = managers.SingleOrDefault(mgr => mgr.EmpGuid == m.EmpGuid);

                if (manager != null)
                {
                    if (!string.IsNullOrEmpty(m.CertificateCode))
                    {
                        if (!titleCode.Split(',').Contains(m.CertificateCode))
                        {
                            titleCode += "," + m.CertificateCode;
                            manager.Certificate += string.Format("<br/>{0}:{1}", m.CertificateName, m.CertificateCode);
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(m.CertificateCode))
                    {
                        titleCode += "," + m.CertificateCode;
                        m.StrTitleDetails = string.Format("{0}:{1}", m.CertificateName, m.CertificateCode);
                    }

                    managers.Add(new ManagerProjectInfoDTO()
                    {
                        EmpGuid = m.EmpGuid,
                        Certificate = m.StrTitleDetails,
                        IDCard = m.IDCard,
                        Name = m.Name,
                        ProjectList = ProjectInfoConvert(personDal.GetZtbManagerProjectInfo(m.IDCard))
                    });
                }
            }

            #endregion

            return JsonConvert.SerializeObject(managers);
        }

        private List<DTO.ProjectInfoDTO> ProjectInfoConvert(List<Entity.ProjectInfo> pList)
        {
            return pList.Select(p => new DTO.ProjectInfoDTO
            {
                Type = p.Type,
                Content1 = p.Content1,
                Content2 = p.Content2,
                Content3 = p.Content3
            }).ToList();
        }

        #endregion

        #region 聊城证书审核
        public override DTO.OperationResult EmpCertPost(string corpUserGuid, IList<string> certs, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (log == null)
            {
                result.Result = false;
                result.Message = "参数错误！";
                return result;
            }
            //参数不够使用log传递参数
            int optType = 4;
            int.TryParse(log.FunctionId, out optType);
            string message = log.FunctionType;
            string description = log.Notice;
            return EmpCertPostOrAudit(corpUserGuid, certs, optType, areaCode, message, description);
        }

        /// <summary>
        /// 返回证书审核状态
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="empGuid"></param>
        /// <param name="optType"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetCertFlowCode(string corpUserGuid, string certGuid, int optType, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            bool status = true;//企业状态标识
            try
            {
                ////用户信息
                DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
                if (!result0.Result || result0.ReturnValue == null)
                {
                    result.Result = false;
                    result.Message = "登录用户信息有误！";
                    return result;
                }
                var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
                ////判断人员是否存在
                result = CheckCertIsExist(certGuid);
                if (!result.Result)
                {
                    return result;
                }
                Tb_Emp_TitleDetails_Zbdl currentCert = (Tb_Emp_TitleDetails_Zbdl)result.ReturnValue;
                ////取得审核状态
                List<DTO.OperationResult> resultList = new List<DTO.OperationResult>();
                string area = string.Empty;
                for (int i = 0; i <= optType; i++)
                {
                    if (i > 3)
                    {
                        area = areaCode; ////本地审核状态
                    }
                    OptType opt = (OptType)System.Enum.Parse(typeof(OptType), i.ToString());////当前操作
                    DTO.OperationResult result1 = new OperationResult();
                    var nextFlow = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                   userInfo.RoleID.ToString(), string.Empty,
                                   areaCode, currentCert.ClassID.ToString()
                                   , currentCert.FlowCode, opt);
                    result1.Result = nextFlow.Result;
                    result1.Message = nextFlow.Message;
                    result1.ReturnValue = nextFlow.NextFlowCode;
                    resultList.Add(result1);
                }
                result.Result = true;
                result.ReturnValue = resultList;
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "获取审核状态失败" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        private DTO.OperationResult EmpCertPostOrAudit(string corpUserGuid,
           IList<string> certs,
           int optType,
           string areaCode,
           string message,
           string description
            )
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string empName = "";
            ////用户验证
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result || result0.ReturnValue == null)
            {
                result.Result = false;
                result.Message = "登录用户信息有误！";
                return result;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            try
            {
                foreach (var item in certs)
                {
                    ////判断证书是否存在
                    DTO.OperationResult result1 = CheckCertIsExist(item.Trim());
                    if (!result1.Result)
                    {
                        result.Message += result1.Message;
                        continue;
                    }
                    Tb_Emp_TitleDetails_Zbdl empquality = (Tb_Emp_TitleDetails_Zbdl)result1.ReturnValue;
                    ////判断人员是否存在
                    DTO.OperationResult result2 = CheckEmpIsExist(empquality.EmpGuid.ToString());
                    if (!result2.Result)
                    {
                        result.Message += result2.Message;
                        continue;
                    }
                    tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result2.ReturnValue;
                    ////取得证书审核状态
                    if (empquality.FlowCode == null)
                    {
                        empquality.FlowCode = "0";
                    }
                    OptType opt = (OptType)System.Enum.Parse(typeof(OptType), optType.ToString());////当前操作
                    ////返回flowcode状态
                    var nextflow = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                   userInfo.RoleID.ToString(), string.Empty,
                                   areaCode,
                                   empquality.ClassID == null ? "2611" : empquality.ClassID.ToString(), empquality.FlowCode, opt);
                    if (!nextflow.Result)
                    {
                        result.Message += nextflow.Message;
                        continue;
                    }
                    string nextCode = nextflow.NextFlowCode.ToString();
                    if (string.IsNullOrEmpty(nextCode))
                    {
                        continue;
                    }
                    empquality.FlowCode = nextCode;
                    zbdlcontext.SaveChanges();
                    result.Result = true;

                    // result.Message += currentManager.Name + result3.Message;
                    empName += currentManager.Name + empquality.CertificateName + ",";
                    ////日志
                    if (description.Length > 0)
                    {
                        message += "<br/>审核意见：" + description;
                    }
                    var flag = SetUserCertLog(message, empquality, empquality.ClassID == null ? "2611" : empquality.ClassID.ToString(), optType.ToString(), areaCode, corpUserGuid);
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message += currentManager.Name + "日志写入出错！";
                    }
                }
                if (empName.Length > 1)
                {
                    result.Message += "人员[" + empName.TrimEnd(',') + "]操作执行成功！";
                }
                else
                {
                    result.Message += "操作执行失败！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                if (empName.Length > 1)
                {
                    empName = empName.TrimEnd(',');
                    if (result.Message.IndexOf(empName) < 0)
                    {
                        result.Message += "人员[" + empName + "]操作执行成功！";
                    }
                }
                result.Message = message + "失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }

        public override DTO.OperationResult GetCertFlowByGuid(string eduGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result = CheckCertIsExist(eduGuid);
            if (result.Result)
            {
                Tb_Emp_TitleDetails_Zbdl currentcert = (Tb_Emp_TitleDetails_Zbdl)result.ReturnValue;
                if (currentcert != null)
                {
                    result.Result = true;

                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("flowcode", currentcert.FlowCode);
                    dic.Add("classid", currentcert.ClassID == null ? "" : currentcert.ClassID.ToString());
                    result.ReturnValue = dic;
                    result.Message = "获取证书审核状态成功";
                    return result;
                }
                else
                {
                    result.Result = false;
                    result.Message = "获取失败";
                    return result;
                }
            }
            else
            {
                return result;
            }

        }

        private DTO.OperationResult CheckQualityByCertType(Guid empguid, int typeFlag, out int cnt)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            cnt = 0;
            ////查询证书
            var items = zbdlcontext.Emp_Qualities.Where(q => q.EmpGuid == empguid && (q.IsDel == false || q.IsDel == null)).ToList();
            var empQualitie = items.SingleOrDefault(q => q.TypeFlags != null && q.TypeFlags == typeFlag);
            if (empQualitie == null)
            {
                result.Result = false;
                result.Message = "证书信息不存在！";
                return result;
            }
            cnt = items.Count;
            result.Result = true;
            result.ReturnValue = empQualitie;
            return result;
        }

        /// <summary>
        /// 判断证书是否存在
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckCertIsExist(string eduGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(eduGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "证书信息不正确！";
                return result;
            }
            ////查询
            Tb_Emp_TitleDetails_Zbdl currentCert = zbdlcontext.Emp_Qualities.Where(m => (m.IsDel == false || m.IsDel == null) && m.EducationGUID == eGuid).FirstOrDefault();
            if (currentCert == null)
            {
                result.Result = false;
                result.Message = "证书信息不存在！";
                return result;
            }
            result.Result = true;
            result.ReturnValue = currentCert;
            return result;
        }


        #endregion

        #region 聊城职称信息审核
        /// <summary>
        /// 职称信息上报、审核
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="certs"></param>
        /// <param name="log"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpPostInfoPost(string corpUserGuid, IList<string> certs, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (log == null)
            {
                result.Result = false;
                result.Message = "参数错误！";
                return result;
            }
            //参数不够使用log传递参数
            int optType = 4;
            int.TryParse(log.FunctionId, out optType);
            string message = log.FunctionType;
            string description = log.Notice;
            return EmpPostInfoPostOrAudit(corpUserGuid, certs, optType, areaCode, message, description);
        }

        private DTO.OperationResult EmpPostInfoPostOrAudit(string corpUserGuid,
           IList<string> certs,
           int optType,
           string areaCode,
           string message,
           string description
            )
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string empName = "";
            ////用户验证
            DTO.OperationResult result0 = CheckUserIsExist(corpUserGuid);
            if (!result0.Result || result0.ReturnValue == null)
            {
                result.Result = false;
                result.Message = "登录用户信息有误！";
                return result;
            }
            var userInfo = (T_Sys_Users_Zbdl)result0.ReturnValue;
            try
            {
                foreach (var item in certs)
                {
                    ////判断证书是否存在
                    DTO.OperationResult result1 = CheckPostInfoIsExist(item.Trim());
                    if (!result1.Result)
                    {
                        result.Message += result1.Message;
                        continue;
                    }
                    Tb_Emp_Post_Zbdl postInfo = (Tb_Emp_Post_Zbdl)result1.ReturnValue;
                    ////判断人员是否存在
                    DTO.OperationResult result2 = CheckEmpIsExist(postInfo.EmpGuid.ToString());
                    if (!result2.Result)
                    {
                        result.Message += result2.Message;
                        continue;
                    }
                    tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result2.ReturnValue;
                    ////取得证书审核状态
                    if (postInfo.FlowCode == null)
                    {
                        postInfo.FlowCode = "0";
                    }
                    OptType opt = (OptType)System.Enum.Parse(typeof(OptType), optType.ToString());////当前操作

                    int? classID = currentManager.ClassId;
                    classID += 100;

                    ////返回flowcode状态
                    var nextflow = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                   userInfo.RoleID.ToString(), string.Empty,
                                   areaCode,
                                   classID.ToString(), postInfo.FlowCode, opt);
                    if (!nextflow.Result)
                    {
                        result.Message += nextflow.Message;
                        continue;
                    }
                    string nextCode = nextflow.NextFlowCode.ToString();
                    if (string.IsNullOrEmpty(nextCode))
                    {
                        continue;
                    }
                    postInfo.FlowCode = nextCode;
                    zbdlcontext.SaveChanges();
                    result.Result = true;

                    // empName += currentManager.Name + postInfo.CertificateName + ",";
                    empName += currentManager.Name + ",";
                    ////日志
                    if (description.Length > 0)
                    {
                        message += "<br/>审核意见：" + description;
                    }
                    var flag = SetUserPostLog(message,postInfo,classID.ToString(),optType.ToString(), areaCode,corpUserGuid);
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message += currentManager.Name + "日志写入出错！";
                    }
                }
                if (empName.Length > 1)
                {
                    result.Message += "人员[" + empName.TrimEnd(',') + "]操作执行成功！";
                }
                else
                {
                    result.Message += "操作执行失败！";
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                if (empName.Length > 1)
                {
                    empName = empName.TrimEnd(',');
                    if (result.Message.IndexOf(empName) < 0)
                    {
                        result.Message += "人员[" + empName + "]操作执行成功！";
                    }
                }
                result.Message = message + "失败：" + ex.Message;
                result.Result = false;
                result.ReturnValue = null;
            }
            result.ReturnValue = null;
            return result;
        }

        /// <summary>
        /// 判断职称信息是否存在
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckPostInfoIsExist(string empGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "职称信息不正确！";
                return result;
            }
            ////查询
            //Tb_Emp_TitleDetails_Zbdl currentCert = zbdlcontext.Emp_Qualities.Where(m => (m.IsDel == false || m.IsDel == null) && m.EducationGUID == eGuid).FirstOrDefault();
            Tb_Emp_Post_Zbdl post = zbdlcontext.Emp_Post.Where(p => (p.IsDel == false || p.IsDel == null) && p.EmpGuid == eGuid).FirstOrDefault();
            if (post == null)
            {
                result.Result = false;
                result.Message = "职称信息不存在！";
                return result;
            }
            result.Result = true;
            result.ReturnValue = post;
            return result;
        }

        #endregion

        #region 获取人员信息列表 zhjj
        public override List<DTO.tb_Emp_Manager> GetCorpEmpList(string CorpUserGuid, string conditions, int pageCount, int pageSize, out int count)
        {
            count = 0;
            //PersonDALWh personDAL = new PersonDALWh();
            //List<DTO.tb_Emp_Manager> empList = personDAL.GetCorpEmpList(CorpUserGuid, conditions, pageCount, pageSize, out count);
            //if (pageSize != 0)
            //{
            //    return empList.OrderByDescending(m => m.ID).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            //}
            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var query = from m in dbEmp
                        join t in zbdlcontext.Emp_Qualities
                        on m.EmpGuid equals t.EmpGuid
                        select new DTO.tb_Emp_Manager
                        {
                            EmpGuid = m.EmpGuid,
                            Name = m.Name,
                            isFreeze = m.isFreeze,
                            CertificateCode = t.CertificateCode,
                            CertificateName = t.CertificateName,
                        };
            List<DTO.tb_Emp_Manager> empList = query.Distinct().ToList();
            count = empList.Count;
            if (pageSize != 0)
            {
                return empList.OrderByDescending(m => m.ID).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();
            }
            return empList;
        }
        #endregion

        #region 聊城新增人员服务
        /// <summary>
        /// 批量导入人员
        /// </summary>
        /// <param name="data"></param>
        /// <param name="GroupID">证书大类型</param>
        /// <param name="corpguserguid">导入企业</param>
        /// <param name="areaCode"></param>
        /// <param name="creator"></param>
        /// <returns></returns>
        public override List<EmpCertificateImportEntity> BatchImportPersonInfo(List<EmpCertificateImportEntity> data, int? GroupID, string corpguserguid, string areaCode, string creator)
        {
            int classId = -1;
            string classIDStr = GetPersonClassID(corpguserguid, "", areaCode);
            int.TryParse(classIDStr, out classId);
            List<EmpCertificateImportEntity> errorList = new List<EmpCertificateImportEntity>();
            Guid userguid = new Guid();
            Guid.TryParse(corpguserguid, out userguid);
            Tb_Corp_CompanyInfo_Zbdl corp = zbdlcontext.Corp_CompanyInfos.Where(r => r.CorpUserGuid == userguid).FirstOrDefault();
            if (corp == null)
                return data;
            //CertificateCacheManager
            foreach (var model in data)
            {
               if(model.IDCard.StartsWith("'"))
               {
                   model.IDCard=model.IDCard.Replace("'","");
               }
               if(model.IDCard.StartsWith("@"))
               {
                   model.IDCard=model.IDCard.Replace("@","");
               }                
                   
                //非法身份证
                if (model.IDCard.Length == 15)
                   model.IDCard= PersonIDCardValid.IDCard15To18(model.IDCard);
                if (!PersonIDCardValid.CheckIDCard(model.IDCard))
                {
                    model.Description = "身份证信息非法";
                    errorList.Add(model);
                    continue;
                }
                Guid empGuid = Guid.NewGuid();
                var empList = zbdlcontext.Emp_Manager.Where(m => m.IDCard == model.IDCard && m.IsDel == false && m.CorpGuid == userguid).ToList();
                bool isExist = false;
                if (empList != null && empList.Count > 0)
                {
                    model.Description = "人员已存在;";
                    empGuid = empList[0].EmpGuid;
                    int.TryParse(empList[0].ClassId == null ? "" : empList[0].ClassId.ToString(), out classId);
                    isExist = true;
                }
                else
                {
                    tb_Emp_Manager_Zbdl entity = new tb_Emp_Manager_Zbdl();
                    entity.EmpGuid = empGuid;
                    entity.CorpGuid = userguid;
                    entity.IDCard = model.IDCard.Trim();
                    entity.CreatDate = DateTime.Now;
                    entity.Name = model.Name;
                    DateTime bir_date = PersonIDCardValid.GetBirthdaybyIDCard(model.IDCard, true);
                    entity.Birthday = bir_date;
                    entity.BithdayMonth = bir_date.Month;
                    entity.BithdayYear = bir_date.Year;
                    entity.FlowCode = "0";
                    entity.IsDel = false;
                    entity.ClassId = classId;
                    entity.TypeFlag = "-1";
                    entity.GroupID = GroupID;
                    entity.AreaCode = corp.AreaCode;
                    entity.Remark = "import";
                    entity.Sex = Convert.ToByte(PersonIDCardValid.GetSexbyIDCard(model.IDCard, true));
                    zbdlcontext.Configuration.AutoDetectChangesEnabled = false;
                    zbdlcontext.Emp_Manager.Add(entity);
                    //添加审核记录
                    Entity.ZBDLRY.Tb_FlowCode_Zbdl flow = new Entity.ZBDLRY.Tb_FlowCode_Zbdl
                    {
                        AreaCode = "14",
                        CodeType = corp.classID + 10,
                        FlowCode = "0",
                        IsDel = false,
                        ObjectId = entity.EmpGuid.ToString(),
                        UpdateTime = DateTime.Now,
                        RoleId = "15",
                        AppID = 101,
                        Description = corp.AreaCode
                    };
                    zbdlcontext.FlowCodes.Add(flow);
                    zbdlcontext.SaveChanges();

                }

                //处理证书   
                if (string.IsNullOrEmpty(model.ZSCode))
                {
                    model.Description = "证书编号为空";
                    errorList.Add(model);
                    continue;
                }
                //证书是否存在
                if (isExist)
                {
                    List<Tb_Emp_TitleDetails_Zbdl> titleList = zbdlcontext.Emp_Qualities.Where(r => r.EmpGuid == empGuid && r.CertificateCode == model.ZSCode && r.IsDel == false).ToList();
                    if (titleList != null && titleList.Count > 0)
                    {
                        ///证书存在
                        model.Description = string.Format("{0},人员证书已存在;", model.Description);
                        errorList.Add(model);
                        continue;
                    }
                }
                
                //保存证书
                Tb_Emp_TitleDetails_Zbdl titleModel = new Tb_Emp_TitleDetails_Zbdl()
                {
                    EducationGUID=Guid.NewGuid(),
                    EmpGuid = empGuid,
                    GroupTreeID = GroupID,
                    IsDel = false,
                    CertificateCode = model.ZSCode,
                    CertificateName = model.ZSName,
                    CSCode=model.ZSspecialty,
                    CLCode=model.ZSLevel,
                    FlowCode="0",
                    StampCode="ZGZSLC",                   
                    ZsEndDate = model.ZSEndTime.Year==1?null:model.ZSEndTime.ToString("yyyy-MM-dd"),
                    ZsRegisterDate = model.ZSGetTime.Year==1?null:model.ZSGetTime.ToString("yyyy-MM-dd"),
                    IsValid=0,
                    ClassID = classId+100,
                    Remark = "import"
                };
                if(model.ZSGetTime.Year > 1)
                  titleModel.GetCertificateDate = model.ZSGetTime;

                CertificateCacheManager.Current.Start();
                List<CertificateCacheEntity> cache = CertificateCacheManager.Current.dataList.Where(r => r.ParentSID == GroupID&&r.Name==model.ZSName.Trim()).ToList();
               if (cache != null && cache.Count > 0)
               {
                   //证书类型
                   CertificateCacheEntity temp = cache[0];
                   int TypeFlags=0;
                   int.TryParse(temp.Code, out TypeFlags);
                   titleModel.TypeFlags = TypeFlags;
                   //证书专业
                   if (string.IsNullOrEmpty(model.ZSspecialty))
                   {
                       temp = cache.Where(r => r.TypeRootCode == "specialty" && r.TypeName == model.ZSspecialty).FirstOrDefault();
                       if (temp != null)
                       {
                           titleModel.CertificateSpecialty = temp.TypeCode;
                       }
                       else titleModel.CertificateSpecialty = "0";
                   }

                   //证书等级
                   if (string.IsNullOrEmpty(model.ZSLevel))
                   {
                       temp = cache.Where(r => r.TypeRootCode == "ZGDJ" && r.TypeName == model.ZSLevel).FirstOrDefault();
                       if (temp != null)
                       {
                           titleModel.CertificateLevel = temp.TypeCode;
                       }
                       else
                       {
                           titleModel.CertificateLevel = "不分等级";
                       }
                   }

               }
               try
               {
                   zbdlcontext.Emp_Qualities.Add(titleModel);
                   zbdlcontext.SaveChanges();
               }
               catch (Exception ex)
               {
                   model.Description += "证书添加失败";
                   errorList.Add(model);
               }
            }

            return errorList;

        }
        /// <summary>
        /// 按证书类别分组取得人员证书列表,主管审核用
        /// </summary>  
        public override List<tb_emp_titledetails_manager> GetEmpCertAuditList(int pageIndex, int pageSize, string conditions, string certList, string areaCode, out int count)
        {
            count = 0;
            return null;
        }

        /// <summary>
        /// 获取聊城人员证书字典信息
        /// </summary>
        /// <param name="zsType"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<CertificateCacheEntity> GetEmpCertificateDict(int zsType, string type)
        {
            List<CertificateCacheEntity> list = new List<CertificateCacheEntity>();
            try
            {
                List<EmpCertificateDict_LiaoCheng> data = new PersonDALWh().GetEmpCertificateDict(zsType, type);
                if (data != null && data.Count > 0)
                {
                    CertificateCacheEntity model = null;
                    foreach (var en in data)
                    {
                        model = new CertificateCacheEntity();
                        EntityHelper.ConvertEntity2OtherEntity<EmpCertificateDict_LiaoCheng, CertificateCacheEntity>(en, model);
                        list.Add(model);
                    }
                }
            }
            catch (Exception ex)
            {

            }

            return list;
        }

        /// <summary>
        /// 获得职称人员列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="certList"></param>
        /// <param name="areaCode"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public override List<DTO.tb_Emp_Manager> GetEmpManagerPostList(int pageCount, int pageSize, string conditions, string certList, string areaCode, out int count)
        {
            List<DTO.tb_Emp_Manager> list = new List<DTO.tb_Emp_Manager>();

            var dbEmp = zbdlcontext.ManagerInfoFlow;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            var dbEmpPost = zbdlcontext.Emp_Post;

            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                         join post in dbEmpPost
                         on emps.EmpGuid equals post.EmpGuid 
                         where emps.IsDel == false && post.Post_psZG != null && post.Post_psZGCode != null
                            && post.IsDel == false && post.Post_psZG != "-1" 
                         select new tb_Emp_Manager()
                         {
                             EmpGuid = emps.EmpGuid,
                             AreaCode = emps.AreaCode,
                             FlowCode = post.FlowCode,
                             corpName = companies.CorpName,
                             Birthday = emps.Birthday,
                             BithdayMonth = emps.BithdayMonth,
                             BithdayYear = emps.BithdayYear,
                             ClassId = emps.ClassId,
                             CorpClassID = emps.CorpClassID,
                             CorpGuid = emps.CorpGuid,
                             CorpID = emps.CorpID,
                             CreatDate = emps.CreatDate,
                             DogID = emps.DogID,
                             DoMajor = emps.DoMajor,
                             Duty = emps.Duty,
                             DutyLevel = emps.Duty,
                             Education = emps.Education,
                             EMail = emps.EMail,
                             empdogid = emps.empdogid,
                             EmployeeType = emps.EmployeeType,
                             GraduatedSchool = emps.GraduatedSchool,
                             ID = emps.ID,
                             IDCard = emps.IDCard,
                             IDType = emps.IDType,
                             InsuranceNum = emps.InsuranceNum,
                             isFreeze = emps.isFreeze,
                             IsLeave = emps.IsLeave,
                             MobileTel = emps.MobileTel,
                             Name = emps.Name,
                             Post_Corp = post.Post_Corp,
                             Post_Major = post.Post_Major,
                             Post_psDate = post.Post_psDate,
                             Post_psOrg = post.Post_psOrg,
                             Post_psZG = post.Post_psZG,
                             Post_psZGCode = post.Post_psZGCode,
                             PostId = post.Id,
                             pwd = emps.pwd,
                             Sex = emps.Sex,
                             SpecialityID = emps.SpecialityID,
                             Tel = emps.Tel,
                             TypeFlag = emps.TypeFlag,
                             ZhiWu = emps.ZhiWu,
                             GroupID = emps.GroupID,
                             IfHaveCA = emps.IfHaveCA,
                             isZZEmp = emps.isZZEmp,
                             AppID = emps.AppID,
                             ICCard = emps.ICCard
                         };

            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoConditionNew>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }

            var result = query.Distinct().OrderBy(e => e).Skip((pageCount - 1) * pageSize).Take(pageSize).ToList();

            Dictionary<string, string> data = (from dic in zbdlcontext.a_PostPszgDefine
                                               select new { dic.Code, dic.Title }).ToDictionary(p => p.Code, p => p.Title);

            foreach (var manager in result)
            {
                if (manager.Post_psZG != null && data.ContainsKey(manager.Post_psZG))
                {
                    manager.Post_Title += data[manager.Post_psZG];
                }
                if (manager.Post_psZGCode != null && data.ContainsKey(manager.Post_psZGCode))
                {
                    manager.Post_Title += data[manager.Post_psZGCode];
                }

                manager.StrFlowCode = GetFlowCodeTitle(manager.FlowCode, (manager.ClassId + 100).ToString(), areaCode);

                list.Add(manager);
            }
            
            count = query.ToList().Count;
            return list;
        }

        /// <summary>
        /// 职称信息上报
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpPostPost(string empGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid empguid = new Guid();
            Guid.TryParse(empGuid, out empguid);
            Tb_Emp_Post_Zbdl empPost = zbdlcontext.Emp_Post.Where(p => p.EmpGuid == empguid && (p.IsDel == false || p.IsDel == null)).FirstOrDefault();
            tb_Emp_Manager_Zbdl manager = zbdlcontext.Emp_Manager.Where(m => m.EmpGuid == empguid).FirstOrDefault();
            T_Sys_Users_Zbdl userInfo = null;
            if (manager != null && manager.CorpGuid != null)
            {
                userInfo = zbdlcontext.T_Sys_Users.Where(u => u.UserGuid == manager.CorpGuid).FirstOrDefault();
            }
            else
            {
                result.Result = false;
                result.Message = "人员信息有误，该人员不属于任一公司";
                return result;
            }

            if (empPost != null && userInfo != null && manager != null)
            {
                ////取得证书审核状态
                if (empPost.FlowCode == null)
                {
                    empPost.FlowCode = "0";
                }
                OptType opt = (OptType)System.Enum.Parse(typeof(OptType), "4");////当前操作
                int? classID = manager.ClassId;
                classID += 100;
                ////返回flowcode状态
                var nextflow = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                               userInfo.RoleID.ToString(), string.Empty,
                               areaCode,
                               manager.ClassId == null ? "2611" : classID.ToString(), empPost.FlowCode, opt);
               
                string nextCode = nextflow.NextFlowCode.ToString();

                if (nextflow.Result)
                {
                    empPost.FlowCode = nextCode;
                    zbdlcontext.SaveChanges();
                    result.Result = true;
                    result.Message = "上报成功!";

                    ////日志
                    var flag = SetUserLog("上报人员职称信息", manager, "03", "4", areaCode, userInfo.UserGuid.ToString());
                    if (!flag)
                    {
                        result.Result = false;
                        result.Message = "日志写入出错！";
                        return result;
                    }
                }
                else
                {
                    result.Result = false;
                    result.Message = nextflow.Message;
                }
            }
            else
            {
                result.Result = false;
                result.Message = "人员不存在职称信息";
            }

            return result;
        }

        /// <summary>
        /// 检查能否上报职称信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CheckEmpPostPostRight(string empGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid empguid = new Guid();
            Guid.TryParse(empGuid, out empguid);
            Tb_Emp_Post_Zbdl empPost = zbdlcontext.Emp_Post.Where(p => p.EmpGuid == empguid && (p.IsDel == false || p.IsDel == null)).FirstOrDefault();
            tb_Emp_Manager_Zbdl manager = zbdlcontext.Emp_Manager.Where(m => m.EmpGuid == empguid).FirstOrDefault();
            T_Sys_Users_Zbdl userInfo = null;
            if (manager != null && manager.CorpGuid != null)
            {
                userInfo = zbdlcontext.T_Sys_Users.Where(u => u.UserGuid == manager.CorpGuid).FirstOrDefault();
            }
            else
            {
                result.Result = true;////新增时没有该人员
                result.Message = "人员信息有误，该人员不属于任一公司";
                return result;
            }

            if (empPost != null)
            {
                ////取得证书审核状态
                if (empPost.FlowCode == null)
                {
                    empPost.FlowCode = "0";
                }
                OptType opt = (OptType)System.Enum.Parse(typeof(OptType), "4");////当前操作
                int? classID = manager.ClassId;
                classID += 100;
                ////返回flowcode状态
                var nextflow = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                               userInfo.RoleID.ToString(), string.Empty,
                               areaCode,
                               manager.ClassId == null ? "2611" : classID.ToString(), empPost.FlowCode, opt);

                string nextCode = nextflow.NextFlowCode.ToString();

                result.Result = nextflow.Result;
                result.Message = nextflow.Message;

            }
            else
            {
                result.Result = true;////新增时没有该人员
                result.Message = "人员不存在职称信息";
            }

            return result;
        }

        /// <summary>
        /// 通过EmpGuid获取人员职称信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.Tb_Emp_Post GetEmpPostByEmpGuid(string empGuid, string areaCode)
        {
            DTO.Tb_Emp_Post post = new Tb_Emp_Post();
            Guid empguid = new Guid();
            Guid.TryParse(empGuid, out empguid);
            Tb_Emp_Post_Zbdl empPost = zbdlcontext.Emp_Post.Where(p => p.EmpGuid == empguid && (p.IsDel == false || p.IsDel == null)).FirstOrDefault();
            tb_Emp_Manager_Zbdl manager = zbdlcontext.Emp_Manager.Where(m => m.EmpGuid == empguid).FirstOrDefault();
            T_Sys_Users_Zbdl userInfo = null;
            if (manager != null && manager.CorpGuid != null)
            {
                userInfo = zbdlcontext.T_Sys_Users.Where(u => u.UserGuid == manager.CorpGuid).FirstOrDefault();
            }

            if (empPost != null && userInfo != null && manager != null)
            {
                string flowCode = empPost.FlowCode;
                int? classID = manager.ClassId;
                classID += 100;
                string strFlowCode = GetFlowCodeTitle(flowCode, classID.ToString(), areaCode);

                EntityHelper.ConvertEntity2OtherEntity(empPost, post);
                post.StrFlowCode = strFlowCode;
            }
            else
            {
                post.StrFlowCode = "未上报";
            }

            return post;
        }

        public override List<DTO.tb_Emp_Manager> GetEmpManagerRepeat(string idCard, string areaCode)
        {
            if (string.IsNullOrEmpty(idCard))
            {
                return null;
            }
            bool isId = Utilities.PersonIDCardValid.CheckIDCard(idCard);
            {
                if (isId == false)
                {
                    return null;
                }
            }
            var dbEmp = zbdlcontext.Emp_Manager;
            var dbCompany = zbdlcontext.CompanyInfoFlow;
            var query = from emps in dbEmp
                        join corps in dbCompany
                        on emps.CorpGuid equals corps.CorpUserGuid
                        where (emps.IsDel == null || emps.IsDel == false)
                        &&(emps.IDCard!=null&&emps.IDCard==idCard)
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = corps.RealFlowCode,
                            corpName = corps.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = corps.classID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,                  
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = corps.OrginazationCode,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            IfHaveCA = emps.IfHaveCA,
                            isZZEmp = emps.isZZEmp,
                            ICCard = emps.ICCard,
                            corpAddress = corps.Address,
                            corpTel = corps.Tel
                            #endregion
                        };
            var result = query.ToList();
            int cnt = result.Count;
            if (cnt > 200)
            {
                result = result.Take(200).ToList();
            }
            if (result != null && result.Count > 0)
            {
                var empGuids = new List<Guid>();
                empGuids = result.Select(q => q.EmpGuid).ToList().Distinct().ToList();
                var queryTitle = (from emps in dbEmp
                                  join qua in zbdlcontext.Emp_Qualities on emps.EmpGuid equals qua.EmpGuid
                                  where empGuids.Contains(emps.EmpGuid) && emps.IsDel == false && qua.IsDel == false
                                  select new Tb_Emp_TitleDetails()
                                  {
                                      #region 封装实体
                                      EmpGuid = emps.EmpGuid,
                                      ID = emps.ID,
                                      TreeID = qua.TreeID,
                                      ClassID = qua.ClassID,
                                      EducationGUID = qua.EducationGUID,
                                      FlowCode = qua.FlowCode,
                                      CertificateName = qua.CertificateName,
                                      TypeFlags = qua.TypeFlags,
                                      EmpType = qua.EmpType,
                                      CertificateCode = qua.CertificateCode,
                                      //CertificateSpecialty = qua.CertificateSpecialty,
                                      CSCode = qua.CSCode,
                                      CertificateLevel = qua.CertificateLevel,
                                      CLCode = qua.CLCode,
                                      StampCode = qua.StampCode,
                                      GetCertificateDate = qua.GetCertificateDate,
                                      IsExport = qua.IsExport,
                                      bSendFlag = qua.bSendFlag,
                                      IsValid = qua.IsValid,
                                      //ZsEndDate = qua.ZsEndDate,
                                      ZsRegisterDate = qua.ZsRegisterDate,
                                      oldid = qua.oldid,
                                      dogid = qua.dogid,
                                      IsDel = qua.IsDel,
                                      RegisterCorpName = qua.RegisterCorpName,
                                      Remark = qua.Remark,
                                      GroupTreeID = qua.GroupTreeID
                                      #endregion
                                  });
                List<Tb_Emp_TitleDetails> tds = queryTitle.ToList();
                var queryPost = from emps in dbEmp
                                join qua in zbdlcontext.Emp_Post on emps.EmpGuid equals qua.EmpGuid
                                where empGuids.Contains(emps.EmpGuid) && emps.IsDel == false && qua.IsDel == false
                                select new Tb_Emp_Post()
                                {
                                    #region 封装实体
                                    EmpGuid = emps.EmpGuid,
                                    Id = qua.Id,
                                    Post_psZG = qua.Post_psZG,
                                    Post_psZGCode = qua.Post_psZGCode,
                                    Post_Corp = qua.Post_Corp,
                                    //Post_psOrg = qua.Post_psDate,
                                    Post_psDate = qua.Post_psDate,
                                    IsDel = qua.IsDel,
                                    FlowCode = qua.FlowCode
                                    #endregion
                                };
                List<Tb_Emp_Post> posts = queryPost.ToList();
                foreach (var emp in result)
                {
                    try
                    {
                        ////人员所在企业审核状态
                        emp.StrFlowCode = GetFlowCodeTitle(emp.FlowCode, (emp.CorpClassID).ToString(), areaCode);
                        List<Tb_Emp_TitleDetails> dlist = tds.Where(r => r.EmpGuid == emp.EmpGuid && r.IsDel == false).ToList();
                        emp.TZZYStr = GetTitleDetailsbyGroupID(dlist, 1401, true);
                        emp.GJGWStr = GetTitleDetailsbyGroupID(dlist, 1402, true);
                        emp.ZYJNStr = GetTitleDetailsbyGroupID(dlist, 1403, true);
                        emp.SafeStr = GetTitleDetailsbyGroupID(dlist, 1404, true);
                        emp.ZCJZSStr = GetTitleDetailsbyGroupID(dlist, 1406, true);
                        emp.JZYJSStr = GetTitleDetailsbyGroupID(dlist, 1407, true);
                        emp.QTJSStr = GetTitleDetailsbyGroupID(dlist, 1408, true);
                        ////职称
                        List<Tb_Emp_Post> plist = posts.Where(r => r.EmpGuid == emp.EmpGuid && r.IsDel == false).ToList();
                        emp.ZCStr = GetPostStr(plist);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            return result;
        }


        /// <summary>
        /// 获得全部人员列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="empguid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Manager> GetAllEmpManagerList(string conditions, int pageCount, int pageSize, string corpguid, string areaCode, out int count)
        {
            Guid corpGuid = new Guid();
            Guid.TryParse(corpguid, out corpGuid);

            var dbEmp = zbdlcontext.Emp_Manager;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            
            var query = from emps in dbEmp
                        join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
                        where emps.CorpGuid == corpGuid && emps.IsDel==false
                        select new tb_Emp_Manager()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,                           
                            corpName = companies.CorpName,
                            Birthday = emps.Birthday,
                            BithdayMonth = emps.BithdayMonth,
                            BithdayYear = emps.BithdayYear,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            CreatDate = emps.CreatDate,
                            DogID = emps.DogID,
                            DoMajor = emps.DoMajor,
                            Duty = emps.Duty,
                            DutyLevel = emps.Duty,
                            Education = emps.Education,
                            EMail = emps.EMail,
                            empdogid = emps.empdogid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            InsuranceNum = emps.InsuranceNum,
                            isFreeze = emps.isFreeze,
                            IsLeave = emps.IsLeave,
                            MobileTel = emps.MobileTel,
                            Name = emps.Name,
                            OrginazationCode = companies.OrginazationCode,
                            pwd = emps.pwd,
                            Sex = emps.Sex,
                            SpecialityID = emps.SpecialityID,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag,
                            ZhiWu = emps.ZhiWu,
                            IfHaveCA = emps.IfHaveCA,
                            isZZEmp = emps.isZZEmp,                           
                            ICCard = emps.ICCard
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<tb_Emp_Manager>(condition);
            }
            var result = query.OrderBy(q => q.EmpGuid).ToList();
            count = result.Count();

            List<DTO.tb_Emp_Manager> list = new List<DTO.tb_Emp_Manager>();
            if (result != null)
            {
                result = result.Skip(pageSize * (pageCount - 1)).Take(pageSize).ToList();

                if (result != null && result.Count > 0)
                {
                    List<Tb_Emp_TitleDetails> tds = this.GetCorpManagerDetails(conditions, corpguid, areaCode);
                    List<Tb_Emp_Post> posts = this.GetCorpManagerPost(conditions, corpguid, areaCode);
                    foreach (tb_Emp_Manager emp in result)
                    {
                       List<Tb_Emp_TitleDetails> dlist= tds.Where(r => r.EmpGuid == emp.EmpGuid&&r.IsDel==false).ToList();
                       emp.TZZYStr = GetTitleDetailsbyGroupID(dlist, 1401, true);
                       emp.GJGWStr = GetTitleDetailsbyGroupID(dlist, 1402, true);
                       emp.ZYJNStr = GetTitleDetailsbyGroupID(dlist, 1403, true);
                       emp.SafeStr = GetTitleDetailsbyGroupID(dlist, 1404, true);
                       emp.ZCJZSStr = GetTitleDetailsbyGroupID(dlist, 1406, true);
                       emp.JZYJSStr =  GetTitleDetailsbyGroupID(dlist, 1407, true);
                       emp.QTJSStr = GetTitleDetailsbyGroupID(dlist, 1408, true);
                       ////职称
                       List<Tb_Emp_Post> plist = posts.Where(r => r.EmpGuid == emp.EmpGuid && r.IsDel == false).ToList();
                       emp.ZCStr = GetPostStr(plist);
                       list.Add(emp);
                    }
                }
            }

            return list;
        }

        private string GetTitleDetailsbyGroupID(List<Tb_Emp_TitleDetails> dlist,int groupid,bool dj)
        {
            StringBuilder sb = new StringBuilder();
            if (dlist != null)
            {              
                List<Tb_Emp_TitleDetails> safeList = dlist.Where(r => r.GroupTreeID == groupid &&r.IsDel==false).ToList();
                if (safeList != null && safeList.Count > 0)
                {
                    foreach (var en in safeList)
                    {
                        if (dj)
                            sb.AppendFormat("{0}<br/>{1}<br/>{2};<br/>", en.CertificateName, en.CertificateCode, en.CLCode);
                        else
                            sb.AppendFormat("{0}<br/>{1};<br/>", en.CertificateName, en.CertificateCode);
                    }
                }
            }
            return sb.ToString();
        }

        private string GetPostStr(List<Tb_Emp_Post> plist)
        {
            Dictionary<string, string> data = (from dic in zbdlcontext.a_PostPszgDefine
                                               select new { dic.Code, dic.Title }).ToDictionary(p => p.Code, p => p.Title);

            StringBuilder sb = new StringBuilder();
            if (plist != null && plist.Count > 0)
            {
                foreach (var en in plist)
                {
                    string post_psZG = string.Empty;
                    string post_psZGCode = string.Empty;
                    if (en.Post_psZG != null && data.ContainsKey(en.Post_psZG))
                    {
                        post_psZG = data[en.Post_psZG];
                    }
                    if (en.Post_psZGCode != null && data.ContainsKey(en.Post_psZGCode))
                    {
                        post_psZGCode = data[en.Post_psZGCode];
                    }
                    sb.AppendFormat("{0}<br/>{1};<br/>", post_psZG, post_psZGCode);
                }
            }
            
            return sb.ToString();
        }
        /// <summary>
        /// 获取企业下人员的证书信息
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="corpguid"></param>
        /// <param name="areaCode"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        private List<Tb_Emp_TitleDetails> GetCorpManagerDetails(string conditions, string corpguid, string areaCode)
        {
            Guid corpGuid = new Guid();
            Guid.TryParse(corpguid, out corpGuid);

            var dbEmp = zbdlcontext.Emp_Manager;
            var dbCompany = zbdlcontext.Corp_CompanyInfos;
            
            var query = from emps in dbEmp
                        join qua in zbdlcontext.Emp_Qualities on emps.EmpGuid equals qua.EmpGuid
                        where emps.CorpGuid == corpGuid && emps.IsDel==false &&qua.IsDel==false
                        select new Tb_Emp_TitleDetails()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,                            
                            ID = emps.ID,
                            TreeID = qua.TreeID,
                            ClassID = qua.ClassID,
                            EducationGUID = qua.EducationGUID,
                            FlowCode = qua.FlowCode,
                            CertificateName = qua.CertificateName,
                            TypeFlags = qua.TypeFlags,
                            EmpType = qua.EmpType,
                            CertificateCode = qua.CertificateCode,
                            //CertificateSpecialty = qua.CertificateSpecialty,
                            CSCode = qua.CSCode,
                            CertificateLevel = qua.CertificateLevel,
                            CLCode = qua.CLCode,
                            StampCode = qua.StampCode,
                            GetCertificateDate = qua.GetCertificateDate,
                            IsExport = qua.IsExport,
                            bSendFlag = qua.bSendFlag,
                            IsValid = qua.IsValid,
                            //ZsEndDate = qua.ZsEndDate,
                            ZsRegisterDate = qua.ZsRegisterDate,
                            oldid = qua.oldid,
                            dogid = qua.dogid,
                            IsDel = qua.IsDel,
                            RegisterCorpName = qua.RegisterCorpName,
                            Remark = qua.Remark,
                            GroupTreeID  = qua.GroupTreeID
                            #endregion
                        };
            //if (!string.IsNullOrEmpty(conditions))
            //{
            //    var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
            //    query = query.BuildCondition<Tb_Emp_TitleDetails>(condition);
            //}
            var result = query.OrderBy(q => q.EmpGuid).ToList();
            return result;
        }

        /// <summary>
        /// 获取企业下人员的职称信息
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="corpguid"></param>
        /// <param name="areaCode"></param>      
        /// <returns></returns>
        private List<Tb_Emp_Post> GetCorpManagerPost(string conditions, string corpguid, string areaCode)
        {
            Guid corpGuid = new Guid();
            Guid.TryParse(corpguid, out corpGuid);          
            var dbEmp = zbdlcontext.Emp_Manager;           

            var query = from emps in dbEmp
                        join qua in zbdlcontext.Emp_Post on emps.EmpGuid equals qua.EmpGuid
                        where emps.CorpGuid == corpGuid && emps.IsDel == false && qua.IsDel == false
                        select new Tb_Emp_Post()
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            Id = qua.Id,
                            Post_psZG = qua.Post_psZG,
                            Post_psZGCode = qua.Post_psZGCode,
                            Post_Corp = qua.Post_Corp,
                            //Post_psOrg = qua.Post_psDate,
                            Post_psDate = qua.Post_psDate,
                            IsDel = qua.IsDel,
                            FlowCode = qua.FlowCode
                            #endregion
                        };
            //if (!string.IsNullOrEmpty(conditions))
            //{
            //    var condition = JsonConvert.DeserializeObject<IList<QueryPersonInfoCondition>>(conditions);
            //    query = query.BuildCondition<Tb_Emp_Post>(condition);
            //}
            var result = query.OrderBy(q => q.EmpGuid).ToList();
            return result;
        }
        
        public override OperationResult GetCorpManager(string corpUserGuid, string areaCode)
        {
            var dbManager=zbdlcontext.Emp_Manager;
            OperationResult ret = new OperationResult();
            ret.Result = false;
            Guid userGuid = Guid.Empty;
            if (!string.IsNullOrEmpty(corpUserGuid))
            {
                if (!Guid.TryParse(corpUserGuid,out userGuid))
                {
                    ret.Message = "参数不正确";
                    return ret;
                }
            }
            var query = from emps in dbManager
                        where (emps.IsDel == null || emps.IsDel == false) && emps.CorpGuid == userGuid
                        && emps.TypeFlag != null && (emps.TypeFlag.Contains("3") || emps.TypeFlag.Contains("4")
                        || emps.TypeFlag.Contains("5") || emps.TypeFlag.Contains("7") || emps.TypeFlag.Contains("8"))
                        select new GuidKeyAndValue
                        {
                            Key = emps.EmpGuid,
                            Value = emps.TypeFlag
                        };
            var list = query.ToList();
            if (!(list.Count > 0))
            {
                ret.Message = "未查询到数据";
                return ret;
            }
            foreach (var item in list)
            {
                string title = string.Empty;
                if (item.Value.Contains("3"))
                {
                    title += "法定代表人";
                }
                if (item.Value.Contains("4"))
                {
                    title += "企业负责人";
                }
                if (item.Value.Contains("5"))
                {
                    title += "技术负责人";
                }
                if (item.Value.Contains("7"))
                {
                    title += "财务负责人";
                }
                if (item.Value.Contains("8"))
                {
                    title += "经营负责人";
                }
                item.Value = title;
            }
            var result = list.ToDictionary(o => o.Key.ToString(), o => o.Value);
            ret.Message = "获取管理人员成功";
            ret.Result = true;
            ret.ReturnValue = JsonConvert.SerializeObject(result);
            return ret;
        }
        #endregion

       

    }
}
